<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dvSwitch Archives - LucD notes</title>
	<atom:link href="https://www.lucd.info/category/vsphere/dvswitch/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.lucd.info/category/vsphere/dvswitch/</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Wed, 08 Apr 2020 10:23:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.9</generator>

<image>
	<url>https://www.lucd.info/wp-content/uploads/2018/12/cropped-120px-Tibetan_Dharmacakra-32x32.png</url>
	<title>dvSwitch Archives - LucD notes</title>
	<link>https://www.lucd.info/category/vsphere/dvswitch/</link>
	<width>32</width>
	<height>32</height>
</image> 
<atom:link rel="hub" href="https://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="https://pubsubhubbub.superfeedr.com"/><atom:link rel="hub" href="https://websubhub.com/hub"/>	<item>
		<title>dvSwitch scripting &#8211; Part 13 &#8211; Export/Restore Config</title>
		<link>https://www.lucd.info/2013/01/31/dvswitch-scripting-part-13-export-restore-config/</link>
					<comments>https://www.lucd.info/2013/01/31/dvswitch-scripting-part-13-export-restore-config/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Thu, 31 Jan 2013 22:12:37 +0000</pubDate>
				<category><![CDATA[config]]></category>
		<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[5.1]]></category>
		<category><![CDATA[export]]></category>
		<category><![CDATA[restore]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=4339</guid>

					<description><![CDATA[One of the exciting new dvSwitch features in vSphere 5.1 is the ability [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>One of the exciting new <strong>dvSwitch</strong> features in <strong>vSphere 5.1</strong> is the ability to <a href="https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&amp;cmd=displayKC&amp;externalId=2034602" target="_blank">export and restore</a> a dvSwitch <strong>configuration</strong>. This new feature is only available through the <strong>vSphere Web Client</strong>.</p>
<p>On <a href="https://www.hypervisor.fr/" target="_blank">Hypervisor.fr</a>, a blog you should have in your RSS reader, there were already posts on how to configure the dvSwitch <a href="https://www.hypervisor.fr/?p=4229" target="_blank">healthcheck</a> and how to do a dvSwitch <a href="https://www.hypervisor.fr/?p=4240" target="_blank">configuration rollback</a> from PowerCLI. But till now, as far as I know, there were no functions to provide the dvSwitch <strong>export/restore</strong> functionality.</p>
<p><a href="https://www.lucd.info/2013/01/31/dvswitch-scripting-part-13-export-import-config/dvsw-export-import/" rel="attachment wp-att-4342"><img fetchpriority="high" decoding="async" class="alignnone  wp-image-4342" alt="dvSw-export-import" src="https://lucd.info/wp-content/uploads/2013/01/dvSw-export-import.png" width="336" height="341" srcset="https://www.lucd.info/wp-content/uploads/2013/01/dvSw-export-import.png 560w, https://www.lucd.info/wp-content/uploads/2013/01/dvSw-export-import-295x300.png 295w" sizes="(max-width: 336px) 100vw, 336px" /></a></p>
<p>Time to make this useful functionality available for the &#8220;<em>PowerCLI automation crowd</em>&#8221; <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><span id="more-4339"></span></p>
<h2>The Script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Export-dvSwConfig {
&lt;#  
.SYNOPSIS  Export a dvSwitch configuration  
.DESCRIPTION The function will export the dvSwitch
  configuration(s) to a file. 
  This requires at least vSphere 5.1.
.NOTES  Author:  Luc Dekens  
.PARAMETER dvSw
  The dvSwitch(es) whose config you want to export.
.PARAMETER Path
  The path to a filename where the config should be
  written to.
.PARAMETER IncludePortgroups
  Switch that indicates if only the dvSwitch configuration
  or the dvSwitch and all portgroups should be exported
.EXAMPLE
  PS&gt; Export-dvSwConfig -Path C:\dvswconfig.xml -IncludePortgroups
.EXAMPLE
   PS&gt; $dvsw | Export-dvSwConfig -Path C:\file.xml
#&gt;

  param(
    [CmdletBinding()]
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [PSObject]$dvSw,
    [String]$Path,
    [Switch]$IncludePortgroups = $false
  )

  begin {
    $si = Get-View ServiceInstance
    $dvSwMgr = Get-View $si.Content.dvSwitchManager
    $selectionTab = @()
  }

  process{
    if($dvSw -is [System.String]){
      $dvSw = Get-VirtualSwitch -Distributed -Name $dvsw
    }
    if($IncludePortgroups){
      $selection = New-Object VMware.Vim.DVPortgroupSelection
      $selection.portgroupKey = Get-VirtualPortGroup -VirtualSwitch $dvsw | %{$_.Key}
      $selection.dvsUuid = $dvsw.ExtensionData.Uuid
      $selectionTab += $selection
    }
    $selection = New-Object VMware.Vim.DVSSelection
    $selection.dvsUuid = $dvsw.ExtensionData.Uuid
    $selectionTab += $selection
  }

  end{
    $dvswSaved = $dvSwMgr.DVSManagerExportEntity($selectionTab)
    $dvswSaved | Export-Clixml -Path $Path
  }
}

function Restore-dvSwConfig {
&lt;#  
.SYNOPSIS  Restores a dvSwitch configuration  
.DESCRIPTION The function will import the dvSwitch
  configuration(s) from a file. 
  This requires at least vSphere 5.1.
.NOTES  Author:  Luc Dekens  
.PARAMETER Path
  The path to a filename where the config is stored.
.PARAMETER IncludePortgroups
  Switch that indicates if only the dvSwitch configuration
  or the dvSwitch and all portgroups should be exported
.EXAMPLE
  PS&gt; Restore-dvSwConfig -Path C:\dvswconfig.xml
#&gt;

  param(
    [CmdletBinding()]
    [Parameter(Mandatory=$true)]
    [String]$Path,
    [Switch]$IncludePortgroups = $false
  )

  process {

    $si = Get-View ServiceInstance
    $dvSwMgr = Get-View $si.Content.dvSwitchManager

    $dvswImport = @()
    Import-Clixml -Path $Path | 
    where{($IncludePortgroups -and $_.EntityType -eq &quot;distributedVirtualPortgroup&quot;) -or 
        $_.EntityType -eq &quot;distributedVirtualSwitch&quot;} | %{
      $info = New-Object VMware.Vim.EntityBackupConfig
      $info.ConfigBlob = $_.ConfigBlob
      $info.ConfigVersion = $_.ConfigVersion
      $info.Container = $_.Container
      $info.EntityType = $_.EntityType
      $info.Key = $_.Key
      $info.Name = $_.Name
      $dvswImport += $info
    }
    $dvSwMgr.DVSManagerImportEntity($dvswImport,&quot;applyToEntitySpecified&quot;) | Out-Null
  }
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 25,37-39</strong>: My cheap way of emulating the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI51/html/about_obn.html" target="_blank">OBN</a> principle.</p>
<p><strong>Line 40-45</strong>: If the <strong>IncludePortgroups</strong> switch is $true, the configuration of the distributed virtual portgroups on the dvSwitch will also be exported.</p>
<p><strong>Line 53</strong>: The object that is returned by the call to the <a href="https://pubs.vmware.com/vsphere-51/topic/com.vmware.wssdk.apiref.doc/vim.dvs.DistributedVirtualSwitchManager.html#exportEntity" target="_blank">DVSManagerExportEntity</a> method is written to a file with the <a href="https://technet.microsoft.com/en-us/library/hh849916.aspx" target="_blank">Export-Clixml</a> cmdlet.</p>
<p><strong>Line 90-95</strong>: The reason why the function copies the properties one-by-one instead of doing the complete object in one go is due to serialisation-deserialisation process that you get with the Export- and Import-Clixml cmdlets. The imported objects all have a type that has a <em>Deserialized</em> suffix in front. There are ways to avoid this, but the is a simple and readable solution.</p>
<h2>Sample Usage</h2>
<p>The use of the functions is quite simple.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$dvSw = Get-VirtualSwitch -Distributed -Name dvSw1
Export-dvSwConfig -dvSw $dvSw  -Path C:\dvSw1.xml</pre><p></p>
<p>By default this will save the configuration of the dvSwitch, but not the portgroups on the dvSwitch.<br />
To include the portgroups, you will have to use the IncludePortgroups switch.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$dvSw = Get-VirtualSwitch -Distributed -Name dvSw1
Export-dvSwConfig -dvSw $dvSw  -Path C:\dvSw1.xml -IncludePortgroups</pre><p></p>
<p>You can also use the function in a pipeline like this</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VirtualSwitch -Distributed -Name dvSw2 | Export-dvSwConfig -Path C:\dvSw2.xm2</pre><p></p>
<p>As you can read in the Annotations, the function uses the PowerShell Export-Clixml cmdlet to write the configuration to a file.<br />
Note that this format is <span style="background-color: #ffff00;">NOT COMPATIBLE</span> with the file format used in the <strong>vSphere Web Client</strong>.</p>
<p>If you want to emulate that format, you have a look at <a href="https://twitter.com/lamw" target="_blank">William Lam</a>&#8216;s post <a href="https://blogs.vmware.com/vsphere/2013/01/automate-backups-of-vds-distributed-portgroup-configurations-in-vsphere-5-1.html" target="_blank">Automate Backups of VDS &amp; Distributed Portgroup Configurations in vSphere 5.1.</a></p>
<p>To restore the configuration of a dvSwitch, and optionally the connected portgroups, is quite similar. A restore can be executed like this.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Restore-dvSwConfig -Path C:\dvsw1.xml -IncludePortgroups</pre><p></p>
<p>Notice that the <strong>IncludePortgroups</strong> switch defines if you want to restore the configuration of the portgroups on the dvSwitch as well.</p>
<p>The 2 methods that are used by these functions have several other possibilities. You can for example also use these files to Import a dvSwitch, but that will be for a later post <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2013/01/31/dvswitch-scripting-part-13-export-restore-config/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Work with E1000E NICs in PowerCLI</title>
		<link>https://www.lucd.info/2012/11/16/work-with-e1000e-nics-in-powercli/</link>
					<comments>https://www.lucd.info/2012/11/16/work-with-e1000e-nics-in-powercli/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Fri, 16 Nov 2012 21:45:27 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[E1000E]]></category>
		<category><![CDATA[Guest OS]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[Windows Server 2012]]></category>
		<category><![CDATA[NIC]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=4192</guid>

					<description><![CDATA[Now that Windows 8 and Windows Server 2012 are readily available , we [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Now that Windows 8 and Windows Server 2012 are readily available , we all want to do some exploring. But if you want to automate the creation of some test VMs for this, you are in for a surprise.</p>
<p>The current <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview" target="_blank">PowerCLI 5.1 Release 1</a> doesn&#8217;t accept the <strong>E1000E</strong> NIC as a Type on the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI51/html/New-NetworkAdapter.html" target="_blank">New-NetworkAdapter</a> cmdlet. Users start hitting this limitation, as can be seen on this PowerCLI Community <a href="https://communities.vmware.com/thread/425872?tstart=0" target="_blank">thread</a>. You can go for the <strong>E1000</strong>, but why settle for less if you can easily script the use of the E1000E NIC from PowerCLI?</p>
<p><img decoding="async" class="alignnone size-full wp-image-4194" title="Intel PRO/1000 CT Desktop Gigabit Ethernet Network Adapter PCI Express NIC" src="https://lucd.info/wp-content/uploads/2012/11/E1000E1.jpg" alt="" width="300" height="150" /></p>
<p>So even though <a href="https://twitter.com/esloof" target="_blank">Eric &#8220;the Scoop Meister&#8221; Sloof</a> debunked the <a href="https://www.ntpro.nl/blog/archives/1932-Myth-E1000-is-faster-than-VMXNET3.html" target="_blank">myth that the E1000/E1000E is faster than the VmxNet3</a>, the <strong>E1000E</strong> is the default NIC type that vSphere gives you when you create a VM for a Windows Server 2012 or Windows 8 VM. Note that the <strong>E1000</strong> apparently uses slightly more CPU resources than the <strong>E1000E</strong>. With the function in this post you can now automate this behavior.</p>
<p><strong><span style="background-color: #ffff00;">Update November 17th 2012</span></strong>: In <a href="https://kb.vmware.com/selfservice/microsites/search.do?cmd=displayKC&amp;docType=kc&amp;externalId=2006859&amp;sliceId=2&amp;docTypeID=DT_KB_1_1&amp;dialogID=494484024&amp;stateId=1%200%20494482444">KB2006859</a> it seems to say that the <strong>VMXNET3</strong> NIC doesn&#8217;t work with <strong>Windows Server 2012</strong> or <strong>Windows 8</strong>. And there have been several blogs (including mine) that picked up this info. But after you apply the <strong>September 2012</strong> patch to your ESXi servers, you can also use a <strong>VMXNET3</strong> NIC for both Windows OS. See <a href="https://blogs.vmware.com/guestosguide/2012/09/windows-8-2.html" target="_blank">here</a> and <a href="https://blogs.vmware.com/guestosguide/2012/09/windows-server-2012-2.html" target="_blank">here</a> for more info.</p>
<p>Thanks to reader <a href="https://alpacapowered.wordpress.com/" target="_blank"><strong>alcapapower</strong></a> for drawing my attention to this (see his remark in the comments below).</p>
<p><span id="more-4192"></span></p>
<h2>The Script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function New-E1000ENic
{
&lt;#
.SYNOPSIS  Add an E1000E NIC to one or more VMs
.DESCRIPTION The function will add an E1000E NIC card to
  each VM that is passed.
.NOTES  Author:  Luc Dekens
.PARAMETER VM
  One or more virtual machines. This parameter accepts
  pipeline input.
.PARAMETER StartConnected
  Wether or not the device is connected when the VM starts
.PARAMETER MacAddress
  MAC address from the allowed range
.PARAMETER WakeOnLan
  Wether or not WOL is enabled on the NIC
.PARAMETER NetworkName
  Name of the network. This can be a portgroup name from a
  VirtualSwitch or from a DistributedSwitch
.PARAMETER DistributedSwitch
  Can only be used in combination with the PortKey.
.PARAMETER PortKey
  The port on the DistributedSwitch where the NIC shall
  connect to.
.EXAMPLE
  PS&gt; New-E1000ENic -VM MyVM -NetworkName pg1
.EXAMPLE
  PS&gt; Get-VM VM | New-E1000ENic -NetworkName pg1
.EXAMPLE
  PS&gt; New-E1000ENic -VM MyVM -DistributedSwitch sw1 -PortKey 100
#&gt;
  param(
    [CmdletBinding(DefaultParametersetName='VirtualSwitch')]
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [PSObject[]]$VM,
    [Switch]$StartConnected = $false,
    [String]$MacAddress,
    [Switch]$WakeOnLan = $false,
    [Parameter(ParameterSetName='NetworkName')]
    [String]$NetworkName,
    [Parameter(ParameterSetName='DistributedSwitch'Mandatory=$true,)]
    [PSObject]$DistributedSwitch,
    [Parameter(ParameterSetName='DistributedSwitch'Mandatory=$true,)]
    [PSObject]$PortKey
  )

  begin{
    $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $dev = New-Object VMware.Vim.VirtualDeviceConfigSpec
    $dev.Operation = &quot;add&quot;
    $dev.Device = New-Object VMware.Vim.VirtualE1000e
    $dev.Device.Connectable = New-Object VMware.Vim.VirtualDeviceConnectInfo
    $dev.Device.Connectable.StartConnected = $StartConnected
    $dev.Device.WakeOnLanEnabled = $WakeOnLan
    switch ($PsCmdlet.ParameterSetName){
      &quot;NetworkName&quot; {
        $pg = Get-VirtualPortGroup -Name $networkName
        if($pg.ExtensionData -is [VMware.Vim.DistributedVirtualPortgroup]){
          $dvPort = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
          $dvPort.port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection
          $dvPort.port.switchUuid = $pg.VirtualSwitch.ExtensionData.Uuid
          $dvPort.port.portgroupKey = $pg.Extensiondata.Key
          $dev.Device.Backing = $dvPort
        }
        else{
          $dev.Device.Backing = New-Object VMware.Vim.VirtualEthernetCardNetworkBackingInfo
          $dev.Device.Backing.DeviceName = $NetworkName
        }
      }
      &quot;DistributedSwitch&quot; {
        if($DistributedSwitch.GetType().Name -eq &quot;string&quot;){
          $DistributedSwitch = Get-VirtualSwitch -Distributed -Name $DistributedSwitch
        }
        $pg = Get-VirtualPortGroup -Distributed -VirtualSwitch $DistributedSwitch |
        where {$_.ExtensionData.Portkeys -contains $PortKey}
        if(!$pg){
          Write-Warning &quot;Portkey $PortKey not found on $DistributedSwitch.Name&quot;
          exit
        }
        $dvPort = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
        $dvPort.port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection
        $dvPort.port.switchUuid = $dvSw.ExtensionData.Uuid
        $dvPort.port.portgroupKey = $pg.Extensiondata.Key
        $dvPort.port.portKey = $PortKey
        $dev.Device.Backing = $dvPort
      }
    }
    if($MacAddress){
      $dev.Device.MacAddress = $MacAddress
    }
    $spec.deviceChange += $dev
  }

  process{
    foreach($client in $VM){
      if($client.GetType().Name -eq &quot;string&quot;){
        $client = Get-VM -Name $client
      }
      if($client.Version -eq &quot;v8&quot;){
        $client.ExtensionData.ReconfigVM($spec)
        if($PortKey){
          $spec.DeviceChange[0].Device.Backing.port.PortKey =
            [int]$spec.DeviceChange[0].Device.Backing.port.PortKey + 1
        }
      }
      else{
        Write-Warning &quot;$client.Name is not HW version 8&quot;
      }
    }
  }
}</pre><p></p>
<h4>Annotation</h4>
<p><strong>Line 39-44</strong>: The function supports two parametersets, <strong>NetworkName</strong> and <strong>DistributedSwitch</strong>. The parameters NetworkName and DistributedSwitch/PortKey belong to different parametersets and can not be used together.</p>
<p><strong>Line 47-91</strong>: The <a href="https://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.vm.ConfigSpec.html" target="_blank">VirtualMachineConfigSpec</a> parameter for the <a href="https://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.VirtualMachine.html#reconfigure">ReconfigVM_Task</a> method is the same for each call, except for the PortKey property (if it is used). For this reason the object is created and configured in the Begin section of the function.</p>
<p><strong>Line 55</strong>: Depending on the parameterset used, different properties need to be set.</p>
<p><strong>Line 58</strong>: If the <strong>NetworkName</strong> is for a portgroup on a <strong>DistributedSwitch</strong> other pproperties need to be set.</p>
<p><strong>Line 71-73</strong>,<strong> 95-97</strong>: A simple implementation of Object By Name</p>
<p><strong>Line 76-79</strong>: If the function gets a <strong>PortKey</strong> that can not be mapped to a PortGroup, the function will exit.</p>
<p><strong>Line 99</strong>: The use of an E1000E NIC requires that the VM is at least on hardware <strong>version 8</strong>.</p>
<p><strong>Line 101-104</strong>: If the function is used to add an E1000E NIC on multiple VMs, and if the PortKey parameter is used, the function will automatically take the next portnumber. Make sure that there are enough free ports available to accommodate all the VMs you pass to the function.</p>
<h2>Sample run</h2>
<p>The function can be used in several ways.</p>
<p>You can call it by passing a <strong>NetworkName</strong> parameter.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vm = Get-VM -Name W2K12
New-E1000ENic -VM $vm -NetworkName Net1 -StartConnected</pre><p></p>
<p><img decoding="async" class="alignnone  wp-image-4209" title="E1000E-1" src="https://lucd.info/wp-content/uploads/2012/11/E1000E-11.png" alt="" width="546" height="317" srcset="https://www.lucd.info/wp-content/uploads/2012/11/E1000E-11.png 682w, https://www.lucd.info/wp-content/uploads/2012/11/E1000E-11-300x174.png 300w" sizes="(max-width: 546px) 100vw, 546px" /></p><pre class="urvanov-syntax-highlighter-plain-tag"></pre><p>And you can also use the function in a pipeline construct.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VM -Name W2K12* |
New-E1000ENic -NetworkName Net1 -StartConnected</pre><p></p>
<p>The <strong>NetworkName</strong> parameter can also point to a portgroup on a DistributedSwitch</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vm = Get-VM -Name W2K12

New-E1000ENic -VM $vm -NetworkName dvPg1 -WakeOnLan -StartConnected</pre><p></p>
<p><img loading="lazy" decoding="async" class="alignnone  wp-image-4208" title="E1000E-2" src="https://lucd.info/wp-content/uploads/2012/11/E1000E-21.png" alt="" width="455" height="197" srcset="https://www.lucd.info/wp-content/uploads/2012/11/E1000E-21.png 569w, https://www.lucd.info/wp-content/uploads/2012/11/E1000E-21-300x129.png 300w" sizes="auto, (max-width: 455px) 100vw, 455px" /></p><pre class="urvanov-syntax-highlighter-plain-tag"></pre><p>You can specify a specific port with the <strong>PortKey</strong> parameter. Note that this parameter always needs to be used together with the <strong>DistributedSwitch</strong> parameter.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vm = Get-VM -Name W2K12
$dvSw = Get-VirtualSwitch -Distributed -Name dvSw1

New-E1000ENic -VM $vm -DistributedSwitch $dvSw -PortKey 101 -StartConnected</pre><p></p>
<p>The function increments the <strong>PortKey</strong> by 1 if you call the function for more than 1 VM. Make sure there are enough <strong>free ports</strong>, starting from the port you pass in PortKey, to accommodate all the VM for which you call the function.</p>
<p>My <a href="https://www.lucd.info/2012/02/14/dvswitch-scripting-part-12-find-free-ports/" target="_blank">dvSwitch scripting – Part 12 – Find free ports</a> post might come in handy here <img decoding="async" src="https://lucd.info/wp-includes/images/smilies/icon_smile.gif" alt=":-)" /></p>
<p><img loading="lazy" decoding="async" class="alignnone  wp-image-4207" title="E1000E-3" src="https://lucd.info/wp-content/uploads/2012/11/E1000E-31.png" alt="" width="412" height="208" srcset="https://www.lucd.info/wp-content/uploads/2012/11/E1000E-31.png 515w, https://www.lucd.info/wp-content/uploads/2012/11/E1000E-31-300x151.png 300w" sizes="auto, (max-width: 412px) 100vw, 412px" /></p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2012/11/16/work-with-e1000e-nics-in-powercli/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>dvSwitch scripting &#8211; Part 12 &#8211; Find free ports</title>
		<link>https://www.lucd.info/2012/02/14/dvswitch-scripting-part-12-find-free-ports/</link>
					<comments>https://www.lucd.info/2012/02/14/dvswitch-scripting-part-12-find-free-ports/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Tue, 14 Feb 2012 20:16:33 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[port]]></category>
		<category><![CDATA[portkey]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3954</guid>

					<description><![CDATA[On the PowerCLI Community there was an interesting question about dvSwitches, portgroups and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>On the <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=discussions&amp;start=0" target="_blank">PowerCLI Community</a> there was an interesting <a href="https://communities.vmware.com/message/1987845#1987845" target="_blank">question</a> about dvSwitches, portgroups and connecting VMs. Turns out you will need to provide a free port to connect a VM&#8217;s NIC to a portgroup on dvSwitch.<br />
Since the solution is a nice follow up on my previous, somewhat lengthy post, called <a href="https://www.lucd.info/2012/01/29/variations-on-a-port/" target="_blank">Variations on a port</a>, I decided to create a short post on the subject in my <a href="https://www.lucd.info/category/vsphere/dvswitch/" target="_blank">dvSwitch series</a>.</p>
<p style="text-align: left;"><strong><span style="background-color: #ffff00;">Update 3th March 2016</span></strong>: added test to capture portgroups with no VM connected to it</p>
<p><span id="more-3954"></span></p>
<p>To connect a VM&#8217;s NIC to a dvSwitch portgroup you can use the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Set-NetworkAdapter.html" target="_blank">Set-NetworkAdapter</a> cmdlet like this.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-vm $vmname | Get-NetworkAdapter |
Set-NetworkAdapter -DistributedSwitch dvSwitch1 -PortKey 403</pre><p></p>
<p>But how do we get that <strong>PortKey</strong> number ?<br />
<a href="https://lucd.info/wp-content/uploads/2012/02/freeport.png"><img decoding="async" class=" wp-image-3906 alignnone" title="variations" src="https://lucd.info/wp-content/uploads/2012/02/freeport.png" alt="" /></a></p>
<p>Since PowerCLI is all about automation, we are not going to use the vSphere client to get the number. Hence the following function.</p>
<h2>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-dvPgFreePort{
&lt;#
.SYNOPSIS  Get free ports on a dvSwitch portgroup
.DESCRIPTION The function will return 1 or more
  free ports on a dvSwitch portgroup
.NOTES  Author:  Luc Dekens
.PARAMETER PortGroup
  Specify the portgroup for which you want to retrieve
  free ports
.PARAMETER Number
  Specify the number of free ports you want to retrieve.
  The default is 1 port. If Number is greater than the
  number of available ports, the function will return all
  available ports
.EXAMPLE
  PS&gt; Get-dvPgFreePort -PortGroup $pg
.EXAMPLE
  PS&gt; Get-dvPgFreePort -PortGroup $pg -Number 5
#&gt;
 
  param(
  [CmdletBinding()]
  [string]$PortGroup,
  [int]$Number = 1
  )
 
  $nicTypes = &quot;VirtualE1000&quot;,&quot;VirtualE1000e&quot;,&quot;VirtualPCNet32&quot;,
  &quot;VirtualVmxnet&quot;,&quot;VirtualVmxnet2&quot;,&quot;VirtualVmxnet3&quot;
  $ports = @{}
 
  $pg = Get-VirtualPortGroup -Distributed -Name $PortGroup
  $pg.ExtensionData.PortKeys | %{$ports.Add($_,$pg.Name)}
 
  if($pg.ExtensionData.Vm){
      Get-View $pg.ExtensionData.Vm | %{
        $nic = $_.Config.Hardware.Device | 
        where {$nicTypes -contains $_.GetType().Name -and
          $_.Backing.GetType().Name -match &quot;Distributed&quot;}
        $nic | %{$ports.Remove($_.Backing.Port.PortKey)}
      }
  }
 
  if($Number -gt $ports.Keys.Count){
    $Number = $ports.Keys.Count
  }
  ($ports.Keys | Sort-Object)[0..($Number - 1)]
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 27-28</strong>: All the possible NIC types</p>
<p><strong>Line 29</strong>: To collect the ports, the script uses a hash table.</p>
<p><strong>Line 32</strong>: The script adds all ports available on the portgroup to the hash table</p>
<p><strong>Line 34</strong>: Skip the following code block when there are no VMs connected to this portgroup</p>
<p><strong>Line 35</strong>: For all the VMs connected to the portgroup, the script will find the NICs connected to this portgroup.</p>
<p><strong>Line 39</strong>: For the NICs that are connected to the portgroup, the script will remove the corresponding portkey from the hash table</p>
<p><strong>Line 43-45</strong>: If the caller asked more ports than there are free on the portgroup, the function will return all the free ports.</p>
<p><strong>Line 46</strong>: The script returns the free ports in ascending order</p>
<p>Sample usage</p>
<p>The use of the function is quite simple. Just pass the name of the portgroup and the number of ports you want returned.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-dvPgFreePort -PortGroup &quot;dvPG12&quot; -Number 5</pre><p></p>
<p>The result is an ordered list of 5 free ports, which you can use on the PortKey parameter of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Set-NetworkAdapter.html" target="_blank">Set-NetworkAdapter</a> cmdlet.</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/02/portkeys.png"><img decoding="async" class=" wp-image-3906 alignnone" title="variations" src="https://lucd.info/wp-content/uploads/2012/02/portkeys.png" alt="" /></a></p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2012/02/14/dvswitch-scripting-part-12-find-free-ports/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Variations on a port</title>
		<link>https://www.lucd.info/2012/01/29/variations-on-a-port/</link>
					<comments>https://www.lucd.info/2012/01/29/variations-on-a-port/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 29 Jan 2012 16:34:11 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[New-VIProperty]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[port]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3891</guid>

					<description><![CDATA[I got an interesting question from one of my co-authors of the PowerCLI [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I got an interesting question from one of my co-authors of the <a href="https://www.powerclibook.com/" target="_blank">PowerCLI Reference</a> book. He was looking for a method to find the <strong>port</strong> used by a <strong>VM</strong> when connected to a <strong>portgroup</strong> on a <a href="https://www.lucd.info/category/vsphere/dvswitch/" target="_blank">dvSwitch</a>.</p>
<p style="text-align: left;">Finding the answer to that question is not too difficult, once you know which property holds the value. But while writing and testing the script, I thought that this question would be a good opportunity to show several ways and methods that you have at your disposal in <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview" target="_blank">PowerCLI</a> and PowerShell, to come to a solution.</p>
<p style="text-align: left;"><a href="https://lucd.info/wp-content/uploads/2012/01/JSBvariations.jpg"><img loading="lazy" decoding="async" class=" wp-image-3906 alignnone" title="variations" src="https://lucd.info/wp-content/uploads/2012/01/JSBvariations.jpg" alt="" width="450" height="188" /></a></p>
<p style="text-align: left;">Here it goes.</p>
<p><span id="more-3891"></span></p>
<h2>The basic solution</h2>
<p>With a bit of (logical) thinking and the help of the <strong>Get-Member</strong> cmdlet, it didn&#8217;t take long to discover where the <a href="https://www.lucd.info/category/vsphere/dvswitch/" target="_blank">dvSwitch</a> port information is hiding.</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/01/VMport.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3926" title="VMport" src="https://lucd.info/wp-content/uploads/2012/01/VMport.png" alt="" width="476" height="313" srcset="https://www.lucd.info/wp-content/uploads/2012/01/VMport.png 529w, https://www.lucd.info/wp-content/uploads/2012/01/VMport-300x197.png 300w" sizes="auto, (max-width: 476px) 100vw, 476px" /></a></p>
<p>As a matter of fact the port information is kept with the <a href="https://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.VirtualMachine.html" target="_blank">VirtualMachine</a> itself, under the virtual devices, in the NIC backing object, which is called <a href="https://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo.html" target="_blank">VirtualEthernetCardDistributedVirtualPortBackingInfo</a>.</p>
<p>A quick-and-dirty script to get the ports could look like this.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">foreach($vm in Get-VM){
  $vm.NetworkAdapters | Select @{N=&quot;VM&quot;;E={$vm.Name}},
  @{N=&quot;NIC&quot;;E={$_.Name}},
  @{N=&quot;PG&quot;;E={$_.NetworkName}},
  @{N=&quot;Port&quot;;E={$_.ExtensionData.Backing.Port.PortKey}}
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 2</strong>: The script loops through all NIC that are defined on a VM</p>
<p>The result will appear on screen and will look something like this.</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/01/port-basic.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3918" title="port-basic" src="https://lucd.info/wp-content/uploads/2012/01/port-basic.png" alt="" width="520" height="160" /></a></p>
<p>Notice that for NICs that are connected to <strong>standard portgroups</strong>, the Port property is left <strong>empty</strong>.</p>
<p>To get the results into a CSV file, you will have to store the results temporarily in a variable, and then, after the ForEach loop, you can pipe this variable to the Export-Csv cmdlet.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$report = foreach($vm in Get-VM){
  $vm.NetworkAdapters | Select @{N=&quot;VM&quot;;E={$vm.Name}},
  @{N=&quot;NIC&quot;;E={$_.Name}},
  @{N=&quot;PG&quot;;E={$_.NetworkName}},
  @{N=&quot;Port&quot;;E={$_.ExtensionData.Backing.Port.PortKey}}
}

$report | Export-Csv &quot;C:\report.csv&quot; -NoTypeInformation -UseCulture</pre><p></p>
<h2>A faster solution</h2>
<p>When you visited the <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=discussions&amp;start=0" target="_blank">PowerCLI Community</a> recently, you might have noticed that there is a <a href="https://communities.vmware.com/poll.jspa?poll=1327" target="_blank">poll</a> going on about &#8216;regular&#8217; and &#8216;fast&#8217; solutions. A &#8216;regular&#8217; solution would be one that uses the PowerCLI cmdlets to retrieve <strong>PowerCLI objects</strong> and a &#8216;fast&#8217; solution is one that uses the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-View.html" target="_blank">Get-View</a> cmdlet to retrieve (read-only copies of) <strong>vSphere objects</strong>.</p>
<p>In bigger environments the difference in execution time between regular and fast solutions might be substantial.</p>
<p>So how would we tackle the problem at hand with a &#8216;fast&#8217; solution ?</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$Nics = &quot;VirtualE1000&quot;,&quot;VirtualE1000e&quot;,&quot;VirtualPCNet32&quot;,&quot;VirtualVmxnet&quot;,&quot;VirtualVmxnet2&quot;,&quot;VirtualVmxnet3&quot;

foreach($vm in (Get-View -ViewType VirtualMachine -Property Name,Network,Config.Hardware.Device)){
  $pgs = @{}
  Get-View $vm.Network | %{
    if($_.Key){$key = $_.Key}else{$key=$_.MoRef.Value}
    $pgs.Add($key,$_.Name)
  }

  $vm.Config.Hardware.Device | where {$Nics -contains $_.GetType().Name} |
  Select @{N=&quot;VM&quot;;E={$vm.Name}},
    @{N=&quot;NIC&quot;;E={$_.DeviceInfo.Label}},
    @{N=&quot;PG&quot;;E={
      if($_.Backing.Port){$key=$_.Backing.Port.PortgroupKey}else{$key=$_.Backing.Network.Value}
      $pgs[$key]}},
    @{N=&quot;Port&quot;;E={$_.Backing.Port.PortKey}}
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1</strong>: To select the NIC devices, out of all other devices connected to the VM, the script will check if the Type of the Device is present in this array. This array contains the typenames of all possible NIC types.</p>
<p><strong>Line 3</strong>: The script retrieves all the VMs. In the Property parameter the script tells the engine to only fetch those specific properties. This will cause a time saving in the execution time.</p>
<p><strong>Line 4-8</strong>: The NIC device object does not have a property with the actual name of the portgroup to which it is connected. There is a property that has a &#8216;key&#8217; for the portgroups. To avoid having to scan the connected portgroups each time to find the name, the script sets up a hash table.</p>
<p><strong>Line 10</strong>: This line will loop through all devices connected to the VM and will only pass the NIC devices to the Select-Object in the following line.</p>
<p><strong>Line 14</strong>: The key that points to the portgroup (see above) is stored in a different property, depending if the portgroup is a regular or a distributed portgroup.</p>
<p><strong>Line 15</strong>: The portgroupname is retrieved from the hash table.</p>
<p>This &#8216;fast&#8217; version of the script looks, and is, more complex than the basic function we showed before. The reason for that is that the script will have to do everything, like finding the portgroupname, by itself. In the basic function, which uses PowerCLI objects, a lot of that work is done by the logic behind the PowerCLI cmdlet.</p>
<p>It makes you appreciate the work the <strong>PowerCLI Dev Team</strong> put in the development of the PowerCLI cmdlets, even more.</p>
<p>The output of this script looks of course exactly the same (besides the order in which the VM object are returned).</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/01/port-fast.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3920" title="port-fast" src="https://lucd.info/wp-content/uploads/2012/01/port-fast.png" alt="" width="531" height="154" srcset="https://www.lucd.info/wp-content/uploads/2012/01/port-fast.png 664w, https://www.lucd.info/wp-content/uploads/2012/01/port-fast-300x87.png 300w" sizes="auto, (max-width: 531px) 100vw, 531px" /></a></p>
<h2>A function</h2>
<p>If we want to report on these port numbers regularly, it is better to write a function around the logic we have from the scripts above. A function will allow us to call the functionality, just like we would call any other cmdlet.</p>
<p>Let&#8217;s create the function in such a way that we can retrieve the port information in 2 ways.</p>
<ul>
<li>Retrieve the port information for one or more VMs (similar to the functions above)</li>
<li>Retrieve the port information for all VMs connected to specific Portgroups</li>
</ul>
<p>By using parameter sets it is quite easy to package both methods in 1 function. Something like this</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-dvVmPort{
&lt;#
.SYNOPSIS  Get the dvSwitch port for a VM network adapter
.DESCRIPTION The function will retrieve the dvSwitch port
  for all network adapters, provided the network adapters
  are connected to a dvSwitch.
.NOTES  Author:  Luc Dekens
.PARAMETER VM
  Specify the virtual machine(s) for whose network adapters
  you want to retrieve the port numbers.
.PARAMETER PortGroup
  Specify the portgroup(s) for which you want to retrieve
  the port numbers for all network adapters that have a
  connection to the portgroup(s)
.EXAMPLE
  PS&gt; Get-dvVmPort
.EXAMPLE
  PS&gt; Get-dvVmPort -VM VM1,VM2,VM3
.EXAMPLE
  PS&gt; Get-VM -Name VM* | Get-dvVmPort
.EXAMPLE
  PS&gt; Get-dvVmPort -PortGroup dvPg1
#&gt;

  [CmdletBinding(DefaultParametersetName=&quot;VM&quot;)]
  param(
  [parameter(ParameterSetName=&quot;VM&quot;,ValueFromPipeline = $true)]
  [PSObject[]]$VM,
  [parameter(ParameterSetName=&quot;Portgroup&quot;)]
  [PSObject[]]$Portgroup
  )

  begin{
    $Nics = &quot;VirtualE1000&quot;,&quot;VirtualE1000e&quot;,&quot;VirtualPCNet32&quot;,&quot;VirtualVmxnet&quot;,
    &quot;VirtualVmxnet2&quot;,&quot;VirtualVmxnet3&quot;
    $pgMask = Get-VirtualPortGroup | Sort-Object -Unique | %{$_.Name}
  }

  process{
    switch($PSCmdlet.ParameterSetName){
      &quot;VM&quot;{
        if($VM){
          if($VM[0] -isnot [String]){
            $VM = $VM | %{$_.Name}
          }
          $names = [string]::Join('|',($VM | %{$_}))
        }
        else{
          $names = &quot;.+&quot; 
        }
        $VMs = @(Get-View -ViewType VirtualMachine -Filter @{&quot;Name&quot;=$names})
      }
      &quot;Portgroup&quot;{
        if($PortGroup[0] -isnot [String]){
          $PortGroup = $PortGroup | %{$_.Name}
        }
        $names = [string]::Join('|',($PortGroup | %{$_}))
        $PortGroups = @(Get-View -ViewType DistributedVirtualPortgroup -Filter @{&quot;Name&quot;=$names})
        $pgMask = $PortGroups | %{$_.Name}
        $VMs = $PortGroups | where {$_.Vm} | %{Get-View -Id $_.Vm} | Sort-Object -Property Name -Unique
      }
    }
    if($VMs){
      foreach($object in $VMs){
        $pgs = @{}
        Get-View $object.Network | %{
          if($_.Key){$key = $_.Key}else{$key = $_.MoRef.Value}
          $pgs.Add($key,$_.Name)
        }

        $object.Config.Hardware.Device | 
        where {$Nics -contains $_.GetType().Name} | %{
          New-Object PSOBject -Property @{
            VM = $object.Name
            NIC = $_.DeviceInfo.Label
            PortGroup = &amp;{
              if($_.Backing.Port){
                $key = $_.Backing.Port.PortgroupKey
              }
              else{
                $key = $_.Backing.Network.Value
              }
              $pgs[$key]
            }
            Port = $_.Backing.Port.PortKey
          } | where {$pgMask -contains $_.PortGroup}
        }
      }
    }
  }
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 27-30</strong>: The function uses 2 parametersets, one to pass VMs and one to pass Portgroups. The default is VMs.</p>
<p><strong>Line 29</strong>: Note that the script doesn&#8217;t accept Portgroups from the pipeline. Implementing such a feature is possible, but would require testing the type of the parameter value. I used the &#8216;keep it simple&#8217; rule <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><strong>Line 34-35</strong>: The script needs to test if the device is a NIC. This array should contain all the possible NIC types a VM can have.</p>
<p><strong>Line 36,59,86</strong>: For the PortGroup parameter the script needs to test if the VM under investigation is connected to the requested portgroup. By default we take all the portgroups. If the PortGroup parameter is used, the script will only report on NICs connected to that portgroup.</p>
<p><strong>Line 40-62</strong>: The Switch statement which handles the 2 parametersets.</p>
<p><strong>Line 43-50</strong>: For the VM parameter the script can handle 1 or more VM names, or 1 or more <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/VirtualMachine.html" target="_blank">VirtualMachineImpl</a> objects.</p>
<p><strong>Line 49</strong>: When no value is passed with the VM parameter, the script will take all VMs known in the connected vCenter. Since the script uses the Get-View cmdlet with the Filter parameter, the regular expression &#8216;.+&#8217; is used to find all VMs.</p>
<p><strong>Line 51,60</strong>: For both parametersets, the script passes a variable $VMs to the code after the Switch statement. The $VMs variable is populated with the VMs for which the portgroup port needs to be reported upon.</p>
<p><strong>Line 57</strong>: The mask for the Get-View <strong>Filter</strong> parameter is generated. It&#8217;s of the form &#8220;vm1|vm2|vm3&#8221;</p>
<p><strong>Line 65-69</strong>: The script uses a hash table to allow the portgroup name to be retrieved  with the portgroup key.</p>
<p><strong>Line 71-86</strong>: For each NIC an object holding the information is generated.</p>
<p><strong>Line 78,81</strong>: Note that the portgroup key is located in different properties, depending if the portgroup is on a regular vSwitch or a distributed vSwitch.</p>
<p>There are several ways you can call the function. Some examples</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-dvVmPort | Sort-Object -Property VM,NIC | Select VM,NIC,PortGroup,Port</pre><p></p>
<p>No parameter is passed, so the <strong>VM</strong> parameterset will be chosen. The function will report on all the available VMs. This will produce the following output.<br />
<a href="https://lucd.info/wp-content/uploads/2012/01/fport-ex1.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3928" title="fport-ex1" src="https://lucd.info/wp-content/uploads/2012/01/fport-ex1.png" alt="" width="558" height="159" srcset="https://www.lucd.info/wp-content/uploads/2012/01/fport-ex1.png 698w, https://www.lucd.info/wp-content/uploads/2012/01/fport-ex1-300x85.png 300w" sizes="auto, (max-width: 558px) 100vw, 558px" /></a></p>
<p>Note that we had to use a Select-Object cmdlet to define the order of the displayed properties. In <strong>PowerShell v2</strong> one doesn&#8217;t have any way to specify the order of the properties defined ona <strong>New-Object</strong> cmdlet. In <strong>PowerShell v3</strong> this will change !</p>
<p>Another example, with a selected set of VM that are passed through the pipeline.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VM -Name &quot;VM[13]&quot; | Get-dvVmPort | Sort-Object -Property VM,NIC | Select VM,NIC,PortGroup,Port</pre><p></p>
<p>This will give</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/01/fport-ex2.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3930" title="fport-ex2" src="https://lucd.info/wp-content/uploads/2012/01/fport-ex2.png" alt="" width="576" height="88" srcset="https://www.lucd.info/wp-content/uploads/2012/01/fport-ex2.png 720w, https://www.lucd.info/wp-content/uploads/2012/01/fport-ex2-300x45.png 300w" sizes="auto, (max-width: 576px) 100vw, 576px" /></a></p>
<p>And finally an example with the <strong>PortGroup</strong> parameterset.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-dvVmPort -Portgroup (Get-VirtualPortGroup -Distributed) |  Select VM,NIC,PortGroup,Port</pre><p></p>
<p>This call will produce a report on all the VMs that have a NIC connected to any of the distributed portgroups.</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/01/fport-ex3.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3931" title="fport-ex3" src="https://lucd.info/wp-content/uploads/2012/01/fport-ex3.png" alt="" width="597" height="126" srcset="https://www.lucd.info/wp-content/uploads/2012/01/fport-ex3.png 746w, https://www.lucd.info/wp-content/uploads/2012/01/fport-ex3-300x63.png 300w" sizes="auto, (max-width: 597px) 100vw, 597px" /></a></p>
<h2>A new property</h2>
<p>If we want to display this port information with each NIC connected to a VM, when we do a <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-NetworkAdapter.html" target="_blank">Get-NetworkAdapter</a>, we can wrap the above logic in a <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/New-VIProperty.html" target="_blank">New-VIProperty</a>.</p>
<p>The <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet allows us to extend the default set of properties that come with a PowerCLI object.</p>
<p>In this case the code is quite simple</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name dvPort -ObjectType NetworkAdapter `
  -Value {
    param($nic)

    $nic.ExtensionData.Backing.Port.PortKey
  } -Force | Out-Null</pre><p></p>
<p>When we do</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VM -Name VM4 | Get-NetworkAdapter | Select Name,NetworkName,dvPort | Format-Table</pre><p></p>
<p>We will get the following.</p>
<p><a href="https://lucd.info/wp-content/uploads/2012/01/newviproperty.png"><img loading="lazy" decoding="async" class="alignnone  wp-image-3933" title="newviproperty" src="https://lucd.info/wp-content/uploads/2012/01/newviproperty.png" alt="" width="536" height="98" srcset="https://www.lucd.info/wp-content/uploads/2012/01/newviproperty.png 670w, https://www.lucd.info/wp-content/uploads/2012/01/newviproperty-300x54.png 300w" sizes="auto, (max-width: 536px) 100vw, 536px" /></a></p>
<p>I hope this showed a bit the numerous possibilities you have with PowerCLI and PowerShell to tackle your vSphere administrative tasks.</p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2012/01/29/variations-on-a-port/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>vSphere 5 Top 10 &#8211; NetIOC</title>
		<link>https://www.lucd.info/2011/12/15/vsphere-5-top-10-netioc/</link>
					<comments>https://www.lucd.info/2011/12/15/vsphere-5-top-10-netioc/#respond</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Thu, 15 Dec 2011 21:16:42 +0000</pubDate>
				<category><![CDATA[2011]]></category>
		<category><![CDATA[Dutch]]></category>
		<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[NetIOC]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[VMUG]]></category>
		<category><![CDATA[vSphere]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3747</guid>

					<description><![CDATA[Another post from our Dutch VMUG Event 2011 presentation. This time it&#8217;s about [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Another post from our <a href="https://vmug.nl/cms/index.php?option=com_content&amp;view=section&amp;layout=blog&amp;id=5&amp;Itemid=55" target="_blank">Dutch VMUG Event 2011 presentation</a>. This time it&#8217;s about number 5 in the Top-10, Network I/O Control. This feature allows <strong>user-defined network resource pools</strong> and end-to-end <strong>QoS</strong>.</p>
<p>Note that this feature requires <strong>distributed Switches</strong> (dvSwitch). In fact I could have also written this post in my <a href="https://www.lucd.info/tag/dvswitch/" target="_blank">dvSwitch series</a> with the title <strong>dvSwitch scripting – Part 10 – NetIOC</strong>.</p>
<h2><span id="more-3747"></span>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function New-dvSwNetworkResourcePool{
&lt;#
.SYNOPSIS Create a user-defined network resource pool
.DESCRIPTION The function will create a user-defined
  resourcepool on a specific dvSwitch.
.NOTES  Author:  Luc Dekens
.PARAMETER dvSw
  The dvSwitch on which the user-defined network resource pool
  will be created.
.PARAMETER Name
  The name of the user-defined network resource pool.
.PARAMETER Description
  The description of the user-defined network resource pool.
.PARAMETER QoSTag
  The QoSTag that will be assigned to the user-defined
  network resource pool. A value from the range 0-7.
.PARAMETER Limit
  The QoSTag that will be assigned to the user-defined
  network resource pool. A value from the range 0-7.
.PARAMETER Shares
  The number of shares allocated. Can be &quot;low&quot;,&quot;normal&quot;,&quot;high&quot;
  or a number (a relative value compared with the shares value
  on other resource pools in case of contention)
.EXAMPLE
  PS&gt; New-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool1&quot; `
  PS&gt;&gt; -Description &quot;Dutch VMUG 2011&quot;
.EXAMPLE
  PS&gt; New-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool2&quot; `
  PS&gt;&gt; -Description &quot;Dutch VMUG 2011&quot; -Shares 75 -QoSTag 3
#&gt;
  param(
  [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
  [VMware.Vim.VmwareDistributedVirtualSwitch]$dvSw,
  [parameter(Position = 1, Mandatory = $true)]
  [string]$Name,
  [parameter(Position = 2)]
  [string]$Description,
  [string]$QoSTag,
  [long]$Limit = -1,
  [string]$Shares = &quot;normal&quot;
  )

  $spec = New-Object VMware.Vim.DVSNetworkResourcePoolConfigSpec
  $spec.Name = $Name
  $spec.Description = $Description
  $spec.Key = &quot;dummy&quot;
  $spec.allocationInfo = New-Object VMware.Vim.DVSNetworkResourcePoolAllocationInfo
  $spec.allocationInfo.Limit = $Limit
  $spec.allocationInfo.priorityTag = &amp;{if($QoSTag){[int]$QoSTag}}
  $spec.allocationInfo.Shares = New-Object VMware.Vim.SharesInfo
  if(&quot;high&quot;,&quot;low&quot;,&quot;normal&quot; -contains $Shares){
    $spec.allocationInfo.Shares.Level = $Shares
  }
  else{
    $spec.allocationInfo.Shares.Level = &quot;custom&quot;
    $spec.allocationInfo.Shares.Shares = [int]$Shares
  }

  $dvSw.AddNetworkResourcePool(@($spec))
}

function Remove-dvSwNetworkResourcePool{
&lt;#
.SYNOPSIS Remove a user-defined network resource pool
.DESCRIPTION The function will remove a user-defined
  resource pool from a specific dvSwitch.
.NOTES  Author:  Luc Dekens
.PARAMETER dvSw
  The dvSwitch on which the user-defined network resource pool
  shall be removed.
.PARAMETER Name
  The name of the user-defined network resource pool.
.EXAMPLE
  PS&gt; Remove-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool1&quot;
#&gt;
  param(
  [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
  [VMware.Vim.VmwareDistributedVirtualSwitch]$dvSw,
  [parameter(Position = 1, Mandatory = $true)]
  [string]$Name
  )

  $pool = $dvSw.NetworkResourcePool | where {$_.Name -eq $Name}
  if($pool){
    $dvSw.RemoveNetworkResourcePool($pool.Key)
  }
}

function Get-dvSwNetworkResourcePool{
&lt;#
.SYNOPSIS Retrieve user-defined network resource pool(s)
.DESCRIPTION The function return all or a specific set
  of user-defined network resource pools from a dvSwitch
.NOTES  Author:  Luc Dekens
.PARAMETER dvSw
  The dvSwitch from which the user-defined network resource pool
  shall be retrieved.
.PARAMETER Name
  The name of the user-defined network resource pool.
  If no name is specified, all user-defined network
  resource pools on the dvSwitch will be returned.
.EXAMPLE
  PS&gt; Get-dvSwNetworkResourcePool -dvSw $dvSw
.EXAMPLE
  PS&gt; Get-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;Net*&quot;
#&gt;
  param(
  [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
  [VMware.Vim.VmwareDistributedVirtualSwitch]$dvSw,
  [parameter(Position = 1)]
  [string]$Name = &quot;*&quot;
  )

  $dvSw.UpdateViewData()
  $dvSw.NetworkResourcePool | where {$_.Name -like $Name} | %{
    New-Object PSObject -Property @{
      Name = $_.Name
      Description = $_.Description
      Limit = $_.AllocationInfo.Limit
      QoSTag = &amp;{if($_.AllocationInfo.PriorityTag -eq 0){&quot;none&quot;}else{$_.AllocationInfo.PriorityTag}}
      Shares = &amp;{if($_.AllocationInfo.Shares.Level -eq &quot;custom&quot;){$_.AllocationInfo.Shares.Shares}else{$_.AllocationInfo.Shares.Level}}
    }
  }
}

function Set-dvSwSIOC{
&lt;#
.SYNOPSIS Enable/disable NetIOC on a dvSw
.DESCRIPTION The function will enable or disable
  I/O Control on a dvSwitch
.NOTES  Author:  Luc Dekens
.PARAMETER dvSw
  The dvSwitch on which I/O Control will be
  enabled/disabled
.PARAMETER Enabled
  A switch that allows control of I/O Control. When
  the switch is $True, IOC will be enabled. If $False
  IOC will be disabled
.EXAMPLE
  PS&gt; Set-dvSwSIOC -dvSw $dvSw -Enabled
#&gt;
  param(
  [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
  [VMware.Vim.VmwareDistributedVirtualSwitch]$dvSw,
  [parameter(Position = 1)]
  [switch]$Enabled
  )

  $dvSw.EnableNetworkResourceManagement($Enabled)
}

function Get-dvSwSIOC{
&lt;#
.SYNOPSIS Retrieve the IOC status
.DESCRIPTION Returns the status of IOC on a dvSwitch
.NOTES  Author:  Luc Dekens
.PARAMETER dvSw
  The dvSwitch from which the status of I/O Control will be
  returned
.EXAMPLE
  PS&gt; Get-dvSwSIOC -dvSw $dvSw -Enabled
#&gt;
  param(
  [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
  [VMware.Vim.VmwareDistributedVirtualSwitch]$dvSw
  )

  $dvSw.UpdateViewData()
  New-Object PSObject -Property @{
    Name = $dvSw.Name
    SIOCEnabled = $dvSw.Config.NetworkResourceManagementEnabled
  }
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 38</strong>: Although the QosTag is an [int], we use the [string] cast. Otherwise the absence of the parameter would set QosTag to 0, which is a valid 802.1p value.</p>
<p><strong>Line 38-40</strong>: The absence of these 3 parameters on a call to the function will create a user-defined network resource pool with the same settings as if the resource pool was created in the vSphere Client.</p>
<p><strong>Line 51-57</strong>: If the Shares parameter is not set to &#8220;normal&#8221;, &#8220;high&#8221; or &#8220;low&#8221;, it will be set to &#8220;custom&#8221; and the Shares value will be used as an [int] value.</p>
<p><strong>Line 80</strong>: The removal of a user-defined network resource pool requires the Name parameter to be set.</p>
<p><strong>Line 111</strong>: If no Name parameter is used, all the user-defined network resource pools on the dvSwitch will be returned.</p>
<p><strong>Line 114</strong>: To get the most recent data, the script refreshes the dvSwitch object.</p>
<p><strong>Line 120</strong>: This test will make sure, that the function returns the same values as displayed in the vSphere Client.</p>
<p><strong>Line 121</strong>: When the Shares level is &#8220;custom&#8221;, the [int] value of the share will be returned.</p>
<h2>Sample usage</h2>
<p>We start with an empty dvSwitch. The Get-dvSwitch function can be found in my <a href="https://www.lucd.info/2009/10/12/dvswitch-scripting-part-2-dvportgroup/" target="_blank">dvSwitch scripting – Part 2 – dvPortgroup</a> post.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NETIOC-initial.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3754" title="NETIOC-initial" src="https://lucd.info/wp-content/uploads/2011/12/NETIOC-initial.png" alt="" width="490" height="196" srcset="https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-initial.png 612w, https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-initial-300x120.png 300w" sizes="auto, (max-width: 490px) 100vw, 490px" /></a></p>
<p>First we get the dvSwitch and we get a list of the current network resource pools.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$dvSw = Get-dvSwitch -DatacenterName &quot;DC1&quot; -dvSwitchName &quot;dvSw1&quot;
Get-dvSwNetworkResourcePool -dvSw $dvSw | ft -AutoSize</pre><p></p>
<p>This will return the system network resource pools.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system-cli.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3755" title="NETIOC-respools-system-cli" src="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system-cli.png" alt="" width="620" height="135" srcset="https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system-cli.png 775w, https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system-cli-300x65.png 300w" sizes="auto, (max-width: 620px) 100vw, 620px" /></a></p>
<p>The same information as we can see in the vSphere Client under <strong>System network resource pools</strong>.</p>
<p>Note that NetIOC is <strong>not enabled</strong> by default.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system2.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3758" title="NETIOC-respools-system" src="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system2.png" alt="" width="626" height="302" srcset="https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system2.png 782w, https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system2-300x145.png 300w" sizes="auto, (max-width: 626px) 100vw, 626px" /></a></p>
<p>Next we create a number of user-defined network resource pools.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool1&quot; -Description &quot;Dutch VMUG 2011&quot;
New-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool2&quot; -Description &quot;Dutch VMUG 2011&quot; -Shares 75 -QoSTag 3
New-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool3&quot; -Description &quot;Dutch VMUG 2011&quot; -Limit 4500
Get-dvSwNetworkResourcePool -dvSw $dvSw | ft -AutoSize</pre><p></p>
<p>The result shows the 3 newly created network resource pools.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3759" title="NETIOC-respools-user" src="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user.png" alt="" width="634" height="177" srcset="https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user.png 793w, https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-300x83.png 300w" sizes="auto, (max-width: 634px) 100vw, 634px" /></a></p>
<p>And we see the same in the vSphere Client.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-VC.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3761" title="NETIOC-respools-user-VC" src="https://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-VC.png" alt="" width="630" height="342" srcset="https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-VC.png 788w, https://www.lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-VC-300x162.png 300w" sizes="auto, (max-width: 630px) 100vw, 630px" /></a></p>
<p>As we noticed earlier, NetIOC is not enabled by default. Let&#8217;s display the current setting.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-dvSwSIOC -dvSw $dvSw | ft -AutoSize</pre><p></p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NetIOC-disabled.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3760" title="NetIOC-disabled" src="https://lucd.info/wp-content/uploads/2011/12/NetIOC-disabled.png" alt="" width="306" height="66" srcset="https://www.lucd.info/wp-content/uploads/2011/12/NetIOC-disabled.png 383w, https://www.lucd.info/wp-content/uploads/2011/12/NetIOC-disabled-300x65.png 300w" sizes="auto, (max-width: 306px) 100vw, 306px" /></a></p>
<p>We change the setting and retrieve the value again</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Set-dvSwSIOC -dvSw $dvSw -Enabled
Get-dvSwSIOC -dvSw $dvSw | ft -AutoSize</pre><p></p>
<p>This gives</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/12/NetIOC-enabled.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3762" title="NetIOC-enabled" src="https://lucd.info/wp-content/uploads/2011/12/NetIOC-enabled.png" alt="" width="226" height="61" /></a></p>
<p>To conclude we will clean up the demo pools and disable NetIOC again.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Set-dvSwSIOC -dvSw $dvSw -Enabled:$false

Remove-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool1&quot;
Remove-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool2&quot;
Remove-dvSwNetworkResourcePool -dvSw $dvSw -Name &quot;NetPool3&quot;</pre><p></p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2011/12/15/vsphere-5-top-10-netioc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>dvSwitch scripting – Part 9 – Traffic Shaping</title>
		<link>https://www.lucd.info/2011/06/11/dvswitch-scripting-part-9-traffic-shaping/</link>
					<comments>https://www.lucd.info/2011/06/11/dvswitch-scripting-part-9-traffic-shaping/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sat, 11 Jun 2011 00:07:13 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Traffic shaping]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[SDK]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3273</guid>

					<description><![CDATA[Another interesting feature of a dvSwitch is the ability to use bidirectional traffic [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong> </strong></p>
<p>Another interesting feature of a dvSwitch is the ability to use <strong>bidirectional traffic shaping</strong>. Besides the outbound traffic shaping that is available on regular virtual switches, with the dvSwitches we can also have<strong> inbound</strong> traffic shaping. The traffic shaping is defined with the three known, classical values: average bandwidth, peak and burst size.</p>
<p>Recently there were some threads in the <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=discussions&amp;start=0" target="_blank">PowerCLI Community</a> that asked how to do this with PowerCLI. Time to add this to our repertoire of PowerCLI dvSwitch functions.</p>
<h2><span id="more-3273"></span></h2>
<h2>Background</h2>
<p>By default traffic shaping is disabled for inbound and outbound traffic.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-TS-default.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3275" title="dvPg-TS-default" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-TS-default.png" alt="" width="548" height="249" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvPg-TS-default.png 685w, https://www.lucd.info/wp-content/uploads/2011/06/dvPg-TS-default-300x136.png 300w" sizes="auto, (max-width: 548px) 100vw, 548px" /></a></p>
<p>To remember the difference between ingress and egress, look at it from the point of view of the dvSwitch; ingress is the traffic from the VM to the switch (i.e. incoming traffic) and egress is from the switch to the VM (i.e. outgoing or exit traffic).</p>
<p>The three parameters to control traffic shaping are:</p>
<ul>
<li>average bandwidth: bits per second averaged over time</li>
<li>peak bandwidth: maximum amount (in kbps) the portgroup can handle</li>
<li>burst size: maximum number of bytes the portgroup is allowed to burst. Is a multiplicative factor that defines how long the bandwidth can exceed the average.</li>
</ul>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvSw-shaping-schematic1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3277" title="dvSw-shaping-schematic" src="https://lucd.info/wp-content/uploads/2011/06/dvSw-shaping-schematic1.png" alt="" width="453" height="203" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvSw-shaping-schematic1.png 453w, https://www.lucd.info/wp-content/uploads/2011/06/dvSw-shaping-schematic1-300x134.png 300w" sizes="auto, (max-width: 453px) 100vw, 453px" /></a></p>
<h2>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Set-dvPgTrafficShaping{
&lt;#
.SYNOPSIS
Configure traffic shaping on a dvSwitch portgroup
.DESCRIPTION
The function will configure ingress (VM to switch)
and egress (switch to VM) traffic shaping for a specific
dvSwitch portgroup
.NOTES
Author:  Luc Dekens
.PARAMETER dvPg
An object that represents a dvPortgroup as returned by the
Get-dVsWPg function
.PARAMETER InShaping
 A switch which indicates if inshaping (ingress) should be
enabled or not
.PARAMETER inAverageKbps
The value, in Kbits/sec, for the ingress average bandwidth.
If the value is -1, the setting will be left unchanged.
.PARAMETER inBurstKB
The value, in Kbytes, for the ingress burst size
If the value is -1, the setting will be left unchanged.
.PARAMETER inPeakKbps
The value, in Kbits/sec, for the ingress peak bandwidth
If the value is -1, the setting will be left unchanged.
.PARAMETER OutShaping
A switch which indicates if outshaping (egress) should be
enabled or not
.PARAMETER outAverageKbps
The value, in Kbits/sec, for the average bandwidth
If the value is -1, the setting will be left unchanged.
.PARAMETER outBurstKB
The value, in Kbytes, for the burst size
If the value is -1, the setting will be left unchanged.
.PARAMETER outPeakKbps
The value, in Kbits/sec, for the peak bandwidth
If the value is -1, the setting will be left unchanged.
.EXAMPLE
PS&gt; Get-dvSwPg $dvSw $dvPgName | `
 &gt;&gt; Set-dvPgTrafficShaping -IShaping:$false `
 &gt;&gt;    -OutShaping -outAverage 100000 `
 &gt;&gt;    -outPeak 100000 `
 &gt;&gt;    -outBurst 102400
#&gt;

   [CmdletBinding()]
   param(
   [parameter(Mandatory = $true, ValueFromPipeline = $true)]
   [PSObject]$dvPg,
   [switch]$InShaping,
   [long]$inAverageKbps,
   [long]$inBurstKB,
   [long]$inPeakKbps,
   [switch]$OutShaping,
   [long]$outAverageKbps,
   [long]$outBurstKB,
   [long]$outPeakKbps
   )

   $spec = New-Object VMware.Vim.DVPortgroupConfigSpec
   $spec.ConfigVersion = $dvPg.Config.ConfigVersion
   $spec.DefaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting
   if($InShaping){
      $spec.DefaultPortConfig.InShapingPolicy = New-Object VMware.Vim.DVSTrafficShapingPolicy
      $spec.DefaultPortConfig.InShapingPolicy.Enabled = New-Object VMware.Vim.BoolPolicy
      $spec.DefaultPortConfig.InShapingPolicy.Enabled.Value = $true
      $spec.DefaultPortConfig.InShapingPolicy.Enabled.Inherited = $false
      if($inAverageKbps -ne -1){
         $spec.DefaultPortConfig.InShapingPolicy.averageBandwidth = New-Object VMware.Vim.LongPolicy
         $spec.DefaultPortConfig.InShapingPolicy.averageBandwidth.Value = $inAverageKbps * 1000
         $spec.DefaultPortConfig.InShapingPolicy.averageBandwidth.Inherited = $false
      }
      if($inBurstKB -ne -1){
         $spec.DefaultPortConfig.InShapingPolicy.burstSize = New-Object VMware.Vim.LongPolicy
         $spec.DefaultPortConfig.InShapingPolicy.burstSize.Value = $inBurstKB * 1KB
         $spec.DefaultPortConfig.InShapingPolicy.burstSize.Inherited = $false
      }
      if($inPeakKbps -ne -1){
         $spec.DefaultPortConfig.InShapingPolicy.peakBandwidth = New-Object VMware.Vim.LongPolicy
         $spec.DefaultPortConfig.InShapingPolicy.peakBandwidth.Value = $inPeakKbps * 1000
         $spec.DefaultPortConfig.InShapingPolicy.peakBandwidth.Inherited = $false
      }
   }
   else{
      $spec.DefaultPortConfig.InShapingPolicy = New-Object VMware.Vim.DVSTrafficShapingPolicy
      $spec.DefaultPortConfig.InShapingPolicy.Enabled = New-Object VMware.Vim.BoolPolicy
      $spec.DefaultPortConfig.InShapingPolicy.Enabled.Value = $false
      $spec.DefaultPortConfig.InShapingPolicy.Enabled.Inherited = $true
   }

   if($OutShaping){
      $spec.DefaultPortConfig.OutShapingPolicy = New-Object VMware.Vim.DVSTrafficShapingPolicy
      $spec.DefaultPortConfig.OutShapingPolicy.Enabled = New-Object VMware.Vim.BoolPolicy
      $spec.DefaultPortConfig.OutShapingPolicy.Enabled.Value = $true
      $spec.DefaultPortConfig.OutShapingPolicy.Enabled.Inherited = $false
      if($outAverageKbps -ne -1){
         $spec.DefaultPortConfig.OutShapingPolicy.averageBandwidth = New-Object VMware.Vim.LongPolicy
         $spec.DefaultPortConfig.OutShapingPolicy.averageBandwidth.Value = $outAverageKbps * 1000
         $spec.DefaultPortConfig.OutShapingPolicy.averageBandwidth.Inherited = $false
      }
      if($outBurstKB -ne -1){
         $spec.DefaultPortConfig.OutShapingPolicy.burstSize = New-Object VMware.Vim.LongPolicy
         $spec.DefaultPortConfig.OutShapingPolicy.burstSize.Value = $outBurstKB * 1KB
         $spec.DefaultPortConfig.OutShapingPolicy.burstSize.Inherited = $false
      }
      if($outPeakKbps -ne -1){
         $spec.DefaultPortConfig.OutShapingPolicy.peakBandwidth = New-Object VMware.Vim.LongPolicy
         $spec.DefaultPortConfig.OutShapingPolicy.peakBandwidth.Value = $outPeakKbps * 1000
         $spec.DefaultPortConfig.OutShapingPolicy.peakBandwidth.Inherited = $false
      }
   }
   else{
      $spec.DefaultPortConfig.OutShapingPolicy = New-Object VMware.Vim.DVSTrafficShapingPolicy
      $spec.DefaultPortConfig.OutShapingPolicy.Enabled = New-Object VMware.Vim.BoolPolicy
      $spec.DefaultPortConfig.OutShapingPolicy.Enabled.Value = $false
      $spec.DefaultPortConfig.OutShapingPolicy.Enabled.Inherited = $true
   }

   $dvPg.ReconfigureDVPortgroup($spec)
}

function Get-dvPgTrafficShaping{
&lt;#
.SYNOPSIS
Returns the traffic shaping settings for a dvSwitch portgroup
.DESCRIPTION
The function will return all traffic shaping settings for a dvSwitch portgroup
.NOTES
Author:  Luc Dekens
.PARAMETER dvPg
An object that represents a dvPortgroup as returned by the
Get-dVsWPg function
.EXAMPLE
PS&gt; Get-dvSwPg $dvSw $dvPgName | Get-dvPgTrafficShaping
#&gt;

   [CmdletBinding()]
   param(
   [parameter(Mandatory = $true, ValueFromPipeline = $true)]
   [PSObject]$dvPg)

   $ts = New-Object PSObject

   $ingress = $dvPg.Config.DefaultPortConfig.InshapingPolicy
   Add-Member -InputObject $ts -Name IngressState -Value $ingress.Enabled.Value -MemberType NoteProperty
   if($ingress.Enabled.Value){
      Add-Member -InputObject $ts -Name &quot;InAverage (Kbps)&quot; -Value ($ingress.AverageBandwidth.Value/1000) -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;InBurst (KB)&quot; -Value ($ingress.BurstSize.Value/1KB) -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;InPeak (Kbps)&quot; -Value ($ingress.PeakBandwidth.Value/1000) -MemberType NoteProperty
   }
   else{
      Add-Member -InputObject $ts -Name &quot;InAverage (Kbps)&quot; -Value &quot;na&quot; -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;InBurst (KB)&quot; -Value &quot;na&quot; -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;InPeak (Kbps)&quot; -Value &quot;na&quot; -MemberType NoteProperty
   }

   $egress = $dvPg.Config.DefaultPortConfig.OutshapingPolicy
   Add-Member -InputObject $ts -Name EgressState -Value $egress.Enabled.Value -MemberType NoteProperty
   if($egress.Enabled.Value){
      Add-Member -InputObject $ts -Name &quot;OutAverage (Kbps)&quot; -Value ($egress.AverageBandwidth.Value/1000) -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;OutBurst (KB)&quot; -Value ($egress.BurstSize.Value/1KB) -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;OutPeak (Kbps)&quot; -Value ($egress.PeakBandwidth.Value/1000) -MemberType NoteProperty
   }
   else{
      Add-Member -InputObject $ts -Name &quot;OutAverage (Kbps)&quot; -Value &quot;na&quot; -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;OutBurst (KB)&quot; -Value &quot;na&quot; -MemberType NoteProperty
      Add-Member -InputObject $ts -Name &quot;OutPeak (Kbps)&quot; -Value &quot;na&quot; -MemberType NoteProperty
   }

   $ts
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1-120</strong>: The Set-dvPgTrafficShaping function</p>
<p><strong>Line 61</strong>: When calling methods on distributed virtual switches it is important to pass the ConfigVersion value of the object.</p>
<p><strong>Line 63-89</strong>: Handles the Ingress settings</p>
<p><strong>Line 91-117</strong>: Handles the Egress settings</p>
<p><strong>Line 67,76,81,88,95,99,104,109,116</strong>: When the network shaping settings are define on the portgroup it is important to indicated that property is not inherited from the dvSwitch.</p>
<p><strong>Line 70,80,98,108</strong>: The function parameters allow to specify the average and peak bandwidth values in the Kbps, while the actual call requires these values to be passed in bps. Note that to convert from Kbps to bps you have to multiply by 1000, not 1024.</p>
<p><strong>Line 75,103</strong>: The function parameters for the burst size expects values in KB, just like in the vSphere Client. The method itself requires these values to be in bytes.</p>
<p><strong>Line 1-120</strong>: The Get-dvPgTrafficShaping function.</p>
<p><strong>Line 143</strong>: The result is returned as PSObject to which the properties with the packet shaping values are added.</p>
<h2>Sample usage</h2>
<p>By default, a new dvSwitch and new dvPortgroup will have traffic shaping disabled.<br />
To get the actual settings we can do</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$dcName = &quot;MyDatacenter&quot;
$dvSwName = &quot;dvSw1&quot;
$dvPgName = &quot;dvPg12&quot;

$dvSw = Get-dvSwitch $dcName $dvSwName
$dvPg = Get-dvSwPg $dvSw $dvPgName

Get-dvPgTrafficShaping -dvPg $dvPg</pre><p></p>
<p>This produces output likes this</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-default.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3291" title="dvPg-default" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-default.png" alt="" width="273" height="116" /></a></p>
<p>Btw, the <strong>Get-dvSwitch</strong> and <strong>Get-dvSwPg</strong> functions are described in previous episodes of my dvSwitch series.</p>
<p>To enable inbound and outbound traffic shaping you can call the function as follows</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$dcName = &quot;MyDatacenter&quot;
$dvSwName = &quot;dvSw1&quot;
$dvPgName = &quot;dvPg12&quot;

$dvSw = Get-dvSwitch $dcName $dvSwName
$dvPg = Get-dvSwPg $dvSw $dvPgName

Set-dvPgTrafficShaping -dvPg $dvPg `
-InShaping -inAverageKbps 100000 -inBurstKB 102400 -inPeakKbps 100000 `
-OutShaping -outAverageKbps 100000 -outBurstKB 102400 -outPeakKbps 100000

$dvPg = Get-dvSwPg $dvSw $dvPgName
Get-dvPgTrafficShaping -dvPg $dvPg</pre><p></p>
<p>This will result in</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-activated.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3293" title="dvPg-activated" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-activated.png" alt="" width="465" height="128" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvPg-activated.png 465w, https://www.lucd.info/wp-content/uploads/2011/06/dvPg-activated-300x82.png 300w" sizes="auto, (max-width: 465px) 100vw, 465px" /></a></p>
<p>And in the vSphere Client this will show as follows.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-activated-client.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3294" title="dvPg-activated-client" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-activated-client.png" alt="" width="573" height="246" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvPg-activated-client.png 637w, https://www.lucd.info/wp-content/uploads/2011/06/dvPg-activated-client-300x128.png 300w" sizes="auto, (max-width: 573px) 100vw, 573px" /></a></p>
<p>Notice how we had to call the <strong>Get-dvSwPg</strong> function again before the <strong>Get-dvPgTrafficShaping</strong> function. This is required to fetch the <strong>actual values</strong> for the portgroup.</p>
<p>To <strong>enable inbound</strong> and <strong>disable outbound</strong> traffic shaping, you can make the following call.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Set-dvPgTrafficShaping -dvPg $dvPg `
   -InShaping -inAverageKbps 100000 -inBurstKB 102400 -inPeakKbps 100000 `
   -OutShaping:$false</pre><p></p>
<p>The result looks like this<br />
<a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-in-activated-client.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3295" title="dvPg-in-activated-client" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-in-activated-client.png" alt="" width="565" height="249" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvPg-in-activated-client.png 628w, https://www.lucd.info/wp-content/uploads/2011/06/dvPg-in-activated-client-300x132.png 300w" sizes="auto, (max-width: 565px) 100vw, 565px" /></a></p>
<p>To change specific values (average/peak/burst) you can use the function as follows</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Set-dvPgTrafficShaping -dvPg $dvPg `
   -InShaping -inAverageKbps -1 -inBurstKB 204800 -inPeakKbps -1 `
   -OutShaping:$false</pre><p></p>
<p>This call only changes the <strong>burst</strong> value, the average and peak values are kept as they are, indicated by the -1 values.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-in-burst-only-client.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3296" title="dvPg-in-burst-only-client" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-in-burst-only-client.png" alt="" width="581" height="249" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvPg-in-burst-only-client.png 645w, https://www.lucd.info/wp-content/uploads/2011/06/dvPg-in-burst-only-client-300x128.png 300w" sizes="auto, (max-width: 581px) 100vw, 581px" /></a></p>
<p>And finally a somewhat more advanced example, we use the Get function combined with the Set function to increase the inbound peak bandwidth with 10%.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$ps = Get-dvPgTrafficShaping -dvPg $dvPg

Set-dvPgTrafficShaping -dvPg $dvPg `
-InShaping -inAverageKbps -1 -inBurstKB -1 -inPeakKbps ($ps.&quot;InPeak (Kbps)&quot; * 1.1) `
-OutShaping:$false</pre><p></p>
<p>The result</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/06/dvPg-in-10perc-peak-client.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3297" title="dvPg-in-10perc-peak-client" src="https://lucd.info/wp-content/uploads/2011/06/dvPg-in-10perc-peak-client.png" alt="" width="586" height="250" srcset="https://www.lucd.info/wp-content/uploads/2011/06/dvPg-in-10perc-peak-client.png 651w, https://www.lucd.info/wp-content/uploads/2011/06/dvPg-in-10perc-peak-client-300x128.png 300w" sizes="auto, (max-width: 586px) 100vw, 586px" /></a></p>
<p>Enjoy!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2011/06/11/dvswitch-scripting-part-9-traffic-shaping/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>dvSwitch scripting &#8211; Part 8 &#8211; Get and Set network adapters</title>
		<link>https://www.lucd.info/2010/03/04/dvswitch-scripting-part-8-get-and-set-network-adapters/</link>
					<comments>https://www.lucd.info/2010/03/04/dvswitch-scripting-part-8-get-and-set-network-adapters/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Thu, 04 Mar 2010 19:03:46 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=1871</guid>

					<description><![CDATA[One of the feature requests that came up in several emails I received [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>One of the feature requests that came up in several emails I received for my dvSwitch series, was how to get and set the network adapters of virtual guests. In the current <a href="https://communities.vmware.com/community/vmtn/vsphere/automationtools/powercli?view=overview" target="_blank" rel="noopener noreferrer">PowerCLI</a> version the <a href="https://www.vmware.com/support/developer/windowstoolkit/wintk40u1/html/Get-NetworkAdapter.html" target="_blank" rel="noopener noreferrer">Get-NetworkAdapter</a> and <a href="https://www.vmware.com/support/developer/windowstoolkit/wintk40u1/html/Set-NetworkAdapter.html" target="_blank" rel="noopener noreferrer">Set-NetworkAdapter</a> cmdlets can not handle <strong>portgroups</strong> on <strong>dvSwitches</strong>.</p>
<p>That is why I created the following two functions, called <strong>Get-dvSwNetworkAdapter</strong> and <strong>Set-dvSwNetworkAdapter</strong>.</p>
<p><span id="more-1871"></span></p>
<h2>The script</h2>
<p>In the functions I tried to emulate the existing Get-NetworkAdapter and Set-NetworkAdapter cmdlets.</p>
<h3><span style="background-color: #ffff00;">Update March 21st 2010</span></h3>
<p><a href="https://www.rtfm-ed.co.uk/" target="_blank" rel="noopener noreferrer">Mike Laverick</a> reported some problems with the original functions when an array of objects was passed as an argument. I have rewritten both functions to handle parameter arrays correctly.</p>
<h3><span style="background-color: #ffff00;">Update June 3rd 2010</span></h3>
<p><a href="http://get-admin.com/blog/" target="_blank" rel="noopener noreferrer">Glenn Sizemore</a>, winner of the <a href="https://blogs.technet.com/b/heyscriptingguy/archive/2010/05/25/revised-final-standings-of-the-2010-scripting-games.aspx" target="_blank" rel="noopener noreferrer">2010 Scripting Games</a>, reworked the functions so that they now work with a standard vSwitch <span style="text-decoration: underline;">and</span> a dvSwitch! See dvSwitchNetworkAdapter for Glenn&#8217;s code.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-dvSwNetworkAdapter{
	param([parameter(Mandatory = $true, ValueFromPipeline = $true)][VMware.VimAutomation.Client20.VirtualMachineImpl[]]$VM
	)

	process{
		$VM | Get-View | %{
			$vmObj = $_
			$vmObj.Config.Hardware.Device | where {&quot;VirtualEthernetCard&quot;,&quot;VirtualVmxnet&quot; -contains $_.GetType().BaseType.Name} | %{
				$net = $_
				New-Object PSObject -Property @{
					MacAddress = $net.MacAddress
					WakeOnLanEnabled = $net.WakeOnLanEnabled
					NetworkName = &amp;{
						if($net.Backing.GetType().Name -eq &quot;VirtualEthernetCardNetworkBackingInfo&quot;){
							(Get-View $_.Backing.network).Name
						}
						else{
							($vmObj.Network | %{Get-View $_} | where{$_.Key -eq $net.Backing.Port.PortgroupKey}).Name
						}
					}
					Type = $net.GetType().Name
					ParentId = $vmObj.MoRef.Type + &quot;-&quot; + $vmObj.MoRef.Value
					ConnectionState = New-Object PSObject -Property @{
						Connected = $net.Connectable.Connected
						StartConnected = $net.Connectable.StartConnected
					}
					Id = $vmObj.MoRef.Type + &quot;-&quot; + $vmObj.MoRef.Value + &quot;/&quot; + $net.Key
					Name = $net.DeviceInfo.Label
				}
			}
		}
	}
}

function Set-dvSwNetworkAdapter{
	param([parameter(Mandatory = $true, ValueFromPipeline = $true)][PSCustomObject[]]$NetworkAdapter,
	[parameter(Mandatory = $true)][string]$NetworkName,
	[switch]$StartConnected,
	[switch]$Connected
	)

	process{
		$NetworkAdapter | %{
			$netAdapter = $_
			$vm = Get-View $netAdapter.ParentId
			$esx = Get-View $vm.Runtime.Host
			$newNet = $esx.Network | %{Get-View $_} | where {$_.Name -eq $NetworkName}
			$spec = New-Object VMware.Vim.VirtualMachineConfigSpec

			$dev = New-Object VMware.Vim.VirtualDeviceConfigSpec
			$dev.operation = &quot;edit&quot;
			$dev.device = $vm.Config.Hardware.Device | where {$_.GetType().Name -eq $netAdapter.Type -and $_.MacAddress -eq $netAdapter.MacAddress}

			# Determine backing type
			switch($newNet.GetType().Name){
				&quot;Network&quot; {
					$dev.device.backing = New-Object VMware.Vim.VirtualEthernetCardNetworkBackingInfo
					$dev.device.backing.deviceName = $NetworkName
				}
				&quot;DistributedVirtualPortgroup&quot; {
					$dev.device.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
					$dev.device.backing.port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection

					$dev.device.backing.port.switchUuid = (Get-View $newNet.Config.DistributedVirtualSwitch).Uuid
					$dev.device.backing.port.portgroupKey = $newNet.Config.Key
				}
			}
			if($Connected -ne $null){
				$dev.Device.Connectable.Connected = $Connected
			}
			if($StartConnected -ne $null){
				$dev.Device.Connectable.StartConnected = $StartConnected
			}
			$spec.deviceChange += $dev
			$taskMoRef = $vm.ReconfigVM_Task($spec)

			$task = Get-View $taskMoRef
			while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
				$task.UpdateViewData(&quot;Info&quot;)
			}
			$returnNetworkAdapter = $netAdapter
			$returnNetworkAdapter.NetworkName = $NetworkName
			$returnNetworkAdapter.ConnectionState.StartConnected = $dev.Device.Connectable.StartConnected
			$returnNetworkAdapter.ConnectionState.Connected = $dev.Device.Connectable.Connected
			$returnNetworkAdapter
		}
	}
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 2</strong>: The <strong>Get-dvSwNetworkAdapter</strong> function requires a single parameter, the virtual machine for which you want to get the network adapter information.</p>
<p><strong>Line 5</strong>: With the Process block the function can act as a filter. In other words, the function can be used in a pipeline construct.</p>
<p><strong>Line 6</strong>: This loop takes care if the VM parameter is an array.</p>
<p><strong>Line 8</strong>: The <strong>Where-Object</strong> filter only allows virtual devices that have the basetype <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.device.VirtualEthernetCard.html" target="_blank" rel="noopener noreferrer">VirtualEthernetCard</a> or <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.device.VirtualVmxnet.html" target="_blank" rel="noopener noreferrer">VirtualVmxnet</a> to enter the script block that follows. By using the basetype the script doesn&#8217;t have to test all the derived objects.</p>
<p><strong>Line 10</strong>: The returned information will be in a PSObject. The PSObject has the same properties that are present in the NetworkAdapterImpl that is returned by the Get-NetworkAdapter cmdlet.</p>
<p><strong>Line 13-19</strong>: The network name has to be retrieved from different properties depending on the fact if the card is connected to vSwitch portgroup or to a dvSwitch portgroup.</p>
<p><strong>Line 23-26</strong>: The ConnectionState property, which is a ConnectInfo object with the Get-NetworkAdapter cmdlet, contains a PSObject. But the property names and the values are the same.</p>
<p><strong>Line 27</strong>: The Id property is constructed from the Id of the virtual machine and the device key of the network card. This is the same as what the Get-NetworkAdapter cmdlet returns.</p>
<p><strong>Line 36-37</strong>: The <strong>Set-dvSwNetworkAdapter</strong> function has two required parameters. A network adapter object, as is returned by the Get-dvSwNetworkAdapter cmdlet, and the name of the portgroup to which the adapter shall be connected. Notice that the NetworkAdapter parameter can be passed via the pipeline.</p>
<p><strong>Line 38-39</strong>: The function has two optional switch parameters, StartConnected and Connected.</p>
<p><strong>Line 41</strong>: With the Process block the function can act as a  filter. In other words, the function can be used in a pipeline  construct.</p>
<p><strong>Line 43</strong>: This loop takes care if the NetworkAdapter parameter  is an array.</p>
<p><strong>Line 47</strong>: This construct looks up the new portgroup to which the network adapter will be connected.</p>
<p><strong>Line 48-67</strong>: These lines prepare the parameters for the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualMachine.html#reconfigure" target="_blank" rel="noopener noreferrer">ReconfigVM_Task</a> method that is used to change the portgroup to which the network card is connected.</p>
<p><strong>Line 52</strong>: The script copies the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.device.VirtualDevice.html" target="_blank" rel="noopener noreferrer">VirtualDevice</a> object into the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.ConfigSpec.html">VirtualMachineConfigSpec</a> object. This action minimises the data that will have to be entered into the properties. On <strong>March 26th 2010</strong> I have added the condition that the MAC address should correspond as well. Otherwise there could eventually be multiple NICs that fit the condition. <strong>Rich</strong>, thanks for the discovery and the correction.</p>
<p><strong>Line 55</strong>: Depending if the new portgroup is on a vSwitch or on a dvSwitch, the Backing property of the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.device.VirtualDevice.html" target="_blank" rel="noopener noreferrer">VirtualDevice</a> is of a different type.</p>
<p><strong>Line 68-73</strong>: These lines take care of the StartConnected and Connected switches.</p>
<p><strong>Line 78-80</strong>: This is the &#8220;standard&#8221; loop to wait for the completion of a Task method.</p>
<p><strong>Line 85</strong>: The function returns the new network adapter information through a PSObject. Similar to what the Get-dvSwNetworkAdapter function does.</p>
<h2>Usage</h2>
<p>Some sample use cases of the two functions.</p>
<h3>Getting adapter information</h3>
<p>Similar to the Get-NetworkAdapter cmdlet you can retrieve information from the network adapter(s).</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vmName = &quot;MyGuest&quot;

Get-dvSwNetworkAdapter -VM (Get-VM $vmName)</pre><p></p>
<p>Returns something like this</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/03/get-dvSwNetworkAdapter1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1880" title="get-dvSwNetworkAdapter" src="https://lucd.info/wp-content/uploads/2010/03/get-dvSwNetworkAdapter1.png" alt="" width="401" height="335" srcset="https://www.lucd.info/wp-content/uploads/2010/03/get-dvSwNetworkAdapter1.png 501w, https://www.lucd.info/wp-content/uploads/2010/03/get-dvSwNetworkAdapter1-300x250.png 300w" sizes="auto, (max-width: 401px) 100vw, 401px" /></a></p>
<h3>Changing the adapters</h3>
<p>To change the portgroup of a network adapter you can use something like this</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vmName = &quot;MyGuest&quot;

Get-dvSwNetworkAdapter -VM (Get-VM $vmName) | where {$_.NetworkName -eq &quot;Net2&quot;} | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;</pre><p></p>
<p>And the changed network adapter will be returned.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/03/set-dvSwNetworkAdapter.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1881" title="set-dvSwNetworkAdapter" src="https://lucd.info/wp-content/uploads/2010/03/set-dvSwNetworkAdapter.png" alt="" width="322" height="81" srcset="https://www.lucd.info/wp-content/uploads/2010/03/set-dvSwNetworkAdapter.png 403w, https://www.lucd.info/wp-content/uploads/2010/03/set-dvSwNetworkAdapter-300x75.png 300w" sizes="auto, (max-width: 322px) 100vw, 322px" /></a></p>
<p>The functions can handle calls of the following formats</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VM -Name &quot;MyVm1&quot; | get-dvSwNetworkAdapter | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;
Get-VM -Name &quot;MyVm*&quot; | get-dvSwNetworkAdapter | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;
Get-dvSwNetworkAdapter -VM (Get-VM MyVm1) | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;
Get-dvSwNetworkAdapter -VM (Get-VM MyVm*) | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;
Get-dvSwNetworkAdapter (Get-VM MyVm) | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;
Get-dvSwNetworkAdapter (Get-VM MyVm*) | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot;
Get-dvSwNetworkAdapter (Get-VM MyVm*) | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot; -StartConnected:$true
Get-dvSwNetworkAdapter -VM (Get-VM MyVm1) | Set-dvSwNetworkAdapter -NetworkName &quot;dvPgNet2&quot; -Connected:$true -StartConnected:$true</pre><p></p>
<h2>Conclusion</h2>
<p>I hope these two functions come in handy in your work with dvSwitches.</p>
<p>And a <strong>word of warning</strong>, the two functions don&#8217;t perform any error checking whatsoever. If you pass no network adapter object to the Set-dvSwNetworkAdapter function, it will fail ! Same if you pass the name of a non-existing portgroup name.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/03/04/dvswitch-scripting-part-8-get-and-set-network-adapters/feed/</wfw:commentRss>
			<slash:comments>23</slash:comments>
		
		
			</item>
		<item>
		<title>dvSwitch scripting – Part 7 – Find portgroup/Change VLAN Id</title>
		<link>https://www.lucd.info/2010/02/08/dvswitch-scripting-part-7-find-portgroupchange-vlan-id/</link>
					<comments>https://www.lucd.info/2010/02/08/dvswitch-scripting-part-7-find-portgroupchange-vlan-id/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Mon, 08 Feb 2010 12:47:21 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=1727</guid>

					<description><![CDATA[In a comment on one of the previous dvSwitch posts, see dvSwitch scripting [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In a comment on one of the previous dvSwitch posts, see <a href="https://lucd.info/?p=515" target="_blank">dvSwitch scripting – Part 2 – dvPortgroup</a>,<strong> Gert</strong> asked how he could check if a portgroup with a specific VLAN Id existed on a distributed virtual switch.</p>
<p>Since a function that allows you to search for a portgroup that meets specific requirements can be quite useful, I decided to create a new function to do just that.</p>
<p>Additionally I will show in this post how you can change the VLAN Id of a specific portgroup.</p>
<p><span id="more-1727"></span></p>
<p>The script that accomplishes this is quite simple.</p>
<p>This is the dvSwitch and portgroup configuration from which we start.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/02/dvSw1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1737" title="dvSw1" src="https://lucd.info/wp-content/uploads/2010/02/dvSw1.png" alt="" width="311" height="248" srcset="https://www.lucd.info/wp-content/uploads/2010/02/dvSw1.png 311w, https://www.lucd.info/wp-content/uploads/2010/02/dvSw1-300x239.png 300w" sizes="auto, (max-width: 311px) 100vw, 311px" /></a></p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-dvSwitch{
	param($dcName,$dvSwName)

	$dcNetFolder = Get-View (Get-Datacenter $dcName | Get-View).NetworkFolder
	$found = $null
	foreach($net in $dcNetFolder.ChildEntity){
		if($net.Type -eq &quot;VmwareDistributedVirtualSwitch&quot;){
			$temp = Get-View $net
			if($temp.Name -eq $dvSwName){
				$found = $temp
			}
		}
	}
	$found
}

function Get-dvSwPg{
	param($dvSw,
		[string]$PGName,
		[int]$VLANnr)

# Search for Portgroup Name
	if($PGName){
		$dvSw.Portgroup | %{Get-View -Id $_} | `
			where{$_.Name -eq $PGName}
	}
# Search for VLAN number
	elseif($VLANnr){
		$dvSw.Portgroup | %{Get-View -Id $_} | `
			where{$_.Config.DefaultPortConfig.Vlan.VlanId -eq $VLANnr}
	}
}

function Set-dvSwPgVLAN{
	param($dvSw, $dvPg, $vlanNr)

	$spec = New-Object VMware.Vim.DVPortgroupConfigSpec
	$spec.defaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting
	$spec.DefaultPortConfig.vlan = New-Object VMware.Vim.VmwareDistributedVirtualSwitchVlanIdSpec
	$spec.defaultPortConfig.vlan.vlanId = $vlanNr

	$dvPg.UpdateViewData()
	$spec.ConfigVersion = $dvPg.Config.ConfigVersion

	$taskMoRef = $dvPg.ReconfigureDVPortgroup_Task($spec)

	$task = Get-View $taskMoRef
	while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
		$task.UpdateViewData(&quot;Info&quot;)
	}
}

$datacenterName = &quot;Home1&quot;
$dvSwitchName = &quot;dvSw1&quot;
$dvSwPgName = &quot;dvPg2&quot;

$dvSw = Get-dvSwitch $datacenterName $dvSwitchName

$dvSwPg = Get-dvSwPg $dvSw -VLANnr 111

if($dvSwPg){
	Set-dvSwPgVLAN $dvSw $dvSwPg 901
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1-15</strong>: The Get-dvSwitch function was already presented in <a href="https://lucd.info/?p=515" target="_blank">Part 2</a> of the dvSwitch series.</p>
<p><strong>Line 18-20</strong>: The <strong>Get-dvSwPg</strong> function uses for now two parameters with which it can look for a specific portgroup. These are the portgroup name and the VLAN id. The function can easily be extended to look for other properties that uniquely distinguish a portgroup. Also note that the function only takes one of the parameters, so it is either the portgroup name or the VLAN Id for now.<br />
<strong>Line 34-51</strong>: The <strong>Set-dvSwPgVLAN</strong> function configures a portgroup with the provided VLAN Id.</p>
<p><strong>Line 42-43</strong>: As always, it is critical to provide the &#8220;current&#8221; config version, otherwise the call to the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.dvs.DistributedVirtualPortgroup.html#reconfigure" target="_blank">ReconfigureDVPortgroup_Task</a> method will fail.</p>
<p><strong>Line 59</strong>: A sample call to the <strong>Get-dvSwPg</strong> function. In this sample the VALN Id is used to find the portgroup. If no matching portgroup is found, the function will returm $null.</p>
<p><strong>Line 62</strong>: A sample call to the <strong>Set-dvSwPgVLAN</strong> function. It changes the VLAN Id from 111 to 902 in this example.</p>
<p>The result of the above script:</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/02/dvSw1-after.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1738" title="dvSw1-after" src="https://lucd.info/wp-content/uploads/2010/02/dvSw1-after.png" alt="" width="315" height="244" srcset="https://www.lucd.info/wp-content/uploads/2010/02/dvSw1-after.png 315w, https://www.lucd.info/wp-content/uploads/2010/02/dvSw1-after-300x232.png 300w" sizes="auto, (max-width: 315px) 100vw, 315px" /></a></p>
<p>Feel free to post comments and questions.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/02/08/dvswitch-scripting-part-7-find-portgroupchange-vlan-id/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>dvSwitch scripting – Part 6 – Private VLAN</title>
		<link>https://www.lucd.info/2010/01/29/dvswitch-scripting-part-6-private-vlan/</link>
					<comments>https://www.lucd.info/2010/01/29/dvswitch-scripting-part-6-private-vlan/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Fri, 29 Jan 2010 21:51:37 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=1639</guid>

					<description><![CDATA[Another post in the dvSwitch series. This time I&#8217;ll tackle the creation and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Another post in the <strong>dvSwitch</strong> series. This time I&#8217;ll tackle the creation and use of a <strong>private VLANs</strong> (PVLAN) on a dvSwitch.</p>
<p>For those that are not that familiar with PVLANs have a look at <a href="https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&amp;cmd=displayKC&amp;externalId=1010691" target="_blank">KB1010691</a>, that article gives a good overview of the PVLAN concept. And there were several sessions during the last VMworld that talked about PVLANs. The most noteworthy being <a href="https://vmworld.com/docs/DOC-3813" target="_blank">TA2525 VMware vSphere 4 Networking Deep Dive</a>.</p>
<p>In short, PVLANs allows <strong>isolation</strong> for guests on a <strong>shared IP subnet</strong>.</p>
<p><span id="more-1639"></span></p>
<p>To use PVLANs on a dvSwitch we need to execute a two-step process:</p>
<ol>
<li>Create the PVLANs on the dvSwitch</li>
<li>Assign a PVLAN to a Portgroup</li>
</ol>
<p>The start configuration is a regular dvSwitch which has three portgroups defined.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/01/no-PVLAN.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1661" title="no-PVLAN" src="https://lucd.info/wp-content/uploads/2010/01/no-PVLAN.png" alt="" width="576" height="285" srcset="https://www.lucd.info/wp-content/uploads/2010/01/no-PVLAN.png 576w, https://www.lucd.info/wp-content/uploads/2010/01/no-PVLAN-300x148.png 300w" sizes="auto, (max-width: 576px) 100vw, 576px" /></a></p>
<p>The dvSwitch has no PVLANs defined.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/01/no-PVLAN-2.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1664" title="no-PVLAN-2" src="https://lucd.info/wp-content/uploads/2010/01/no-PVLAN-2.png" alt="" width="555" height="426" srcset="https://www.lucd.info/wp-content/uploads/2010/01/no-PVLAN-2.png 694w, https://www.lucd.info/wp-content/uploads/2010/01/no-PVLAN-2-300x229.png 300w" sizes="auto, (max-width: 555px) 100vw, 555px" /></a></p>
<h3>PVLAN creation</h3>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-dvSwitch{
	param($dcName,$dvSwName)

	$dcNetFolder = Get-View (Get-Datacenter $dcName | Get-View).NetworkFolder
	$found = $null
	foreach($net in $dcNetFolder.ChildEntity){
		if($net.Type -eq &quot;VmwareDistributedVirtualSwitch&quot;){
			$temp = Get-View $net
			if($temp.Name -eq $dvSwName){
				$found = $temp
			}
		}
	}
	$found
}

function New-dvSwPVLAN{
	param($dvSw, $primaryNr, [int[]] $secondaryNr, [string[]] $secondaryType)

	$spec = New-Object VMware.Vim.VMwareDVSConfigSpec

	# Primary
	$pvlan = New-Object VMware.Vim.VMwareDVSPvlanConfigSpec
	$pvlan.operation = &quot;add&quot;
	$pvlan.pvlanEntry = New-Object VMware.Vim.VMwareDVSPvlanMapEntry
	$pvlan.pvlanEntry.primaryVlanId = $primaryNr
	$pvlan.pvlanEntry.pvlanType = &quot;promiscuous&quot;
	$pvlan.pvlanEntry.secondaryVlanId = $primaryNr
	$spec.PvlanConfigSpec += $pvlan

	# Secondaries
	for($i = 0;$i -lt $secondaryNr.Count; $i++){
		$pvlan = New-Object VMware.Vim.VMwareDVSPvlanConfigSpec
		$pvlan.operation = &quot;add&quot;
		$pvlan.pvlanEntry = New-Object VMware.Vim.VMwareDVSPvlanMapEntry
		$pvlan.pvlanEntry.primaryVlanId = $primaryNr
		$pvlan.pvlanEntry.pvlanType = $secondaryType[$i].ToLower()
		$pvlan.pvlanEntry.secondaryVlanId = $secondaryNr[$i]
		$spec.PvlanConfigSpec += $pvlan
	}

	$dvSw.UpdateViewData()
	$spec.ConfigVersion = $dvSw.Config.ConfigVersion
	$taskMoRef = $dvSw.ReconfigureDvs_Task($spec)

	$task = Get-View $taskMoRef
	while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
		$task.UpdateViewData(&quot;Info&quot;)
	}
}

$datacenterName = &quot;Home1&quot;
$dvSwitchName = &quot;dvSw1&quot;

$dvSw = Get-dvSwitch $datacenterName $dvSwitchName

New-dvSwPVLAN $dvSw 2 102,202 &quot;community&quot;,&quot;isolated&quot;</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1-15</strong>: The Get-dvSwitch function was already discussed in <a href="https://lucd.info/?p=515" target="_blank">Part 2</a> of the dvSwitch series.</p>
<p><strong>Line 18</strong>: The parameters $secondayNr and $secondaryType are defined as arrays. That way the function can handle the creation of multiple secondary PVLANs in one call.</p>
<p><strong>Line 37</strong>: The PVLAN typenames are <strong>case sensitive</strong>! To avoid errors, the script converts the passed typenames to lowercase. Just to make sure <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><strong>Line 42-43</strong>: As with any dvSwitch method, it&#8217;s important to pass the correct <strong>ConfigVersion</strong>. Otherwise you get a message saying &#8220;<em>Cannot complete operation due to concurrent modification by another operation</em>&#8220;.</p>
<p><strong>Line 57</strong>: This sample call creates a Primary PVLAN with VLAN Id 2, a Secondary PVLAN of type Community with VLAN Id 102 and another Secondary PVLAN of type Isolated with VLAN Id 202.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/01/PVLAN-created.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1667" title="PVLAN-created" src="https://lucd.info/wp-content/uploads/2010/01/PVLAN-created.png" alt="" width="553" height="426" srcset="https://www.lucd.info/wp-content/uploads/2010/01/PVLAN-created.png 691w, https://www.lucd.info/wp-content/uploads/2010/01/PVLAN-created-300x230.png 300w" sizes="auto, (max-width: 553px) 100vw, 553px" /></a></p>
<h3>Portgroup assignment</h3>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-dvSwitch{
	param($dcName,$dvSwName)

	$dcNetFolder = Get-View (Get-Datacenter $dcName | Get-View).NetworkFolder
	$found = $null
	foreach($net in $dcNetFolder.ChildEntity){
		if($net.Type -eq &quot;VmwareDistributedVirtualSwitch&quot;){
			$temp = Get-View $net
			if($temp.Name -eq $dvSwName){
				$found = $temp
			}
		}
	}
	$found
}

function Set-dVSwPgPVLAN{
	param($dvSw, $dvPgName, $pvlanNr)

	# Find the portgroup
	$dvSw.Portgroup | % {
		$dvPgTemp = Get-View -Id $_
		if($dvPgTemp.Name -eq $dvPgName){
			$dvPg = $dvPgTemp
		}
	}

	$spec = New-Object VMware.Vim.DVPortgroupConfigSpec
	$spec.defaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting
	$spec.defaultPortConfig.vlan = New-Object VMware.Vim.VmwareDistributedVirtualSwitchPvlanSpec
	$spec.defaultPortConfig.vlan.pvlanId = $pvlanNr

	$dvPg.UpdateViewData()
	$spec.ConfigVersion = $dvPg.Config.ConfigVersion

	$taskMoRef = $dvPg.ReconfigureDVPortgroup_Task($spec)

	$task = Get-View $taskMoRef
	while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
		$task.UpdateViewData(&quot;Info&quot;)
	}
}

$datacenterName = &quot;Home1&quot;
$dvSwitchName = &quot;dvSw1&quot;

$dvSw = Get-dvSwitch $datacenterName $dvSwitchName

Set-dvSwPgPVLAN $dvSw &quot;dvPG1&quot; 2
Set-dvSwPgPVLAN $dvSw &quot;dvPG2&quot; 102
Set-dvSwPgPVLAN $dvSw &quot;dvPG3&quot; 202</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1-15</strong>: The Get-dvSwitch function was already discussed in <a href="https://lucd.info/?p=515" target="_blank">Part 2</a> of the dvSwitch series.</p>
<p><strong>Line 20-26</strong>: The scripts looks for the DistributedVirtualPortgroup object in order to pass the correct ConfigVersion (see line 34).</p>
<p><strong>Line 49-51</strong>: The call to the dvSwPgPVLAN requires you to pass the portgroupname and Secondary PVLAN Id.</p>
<p>The final result, the three portgroups have now each been assigned to a PVLAN.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/01/PG-PVLAN-assigned.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1671" title="PG-PVLAN-assigned" src="https://lucd.info/wp-content/uploads/2010/01/PG-PVLAN-assigned.png" alt="" width="576" height="292" srcset="https://www.lucd.info/wp-content/uploads/2010/01/PG-PVLAN-assigned.png 576w, https://www.lucd.info/wp-content/uploads/2010/01/PG-PVLAN-assigned-300x152.png 300w" sizes="auto, (max-width: 576px) 100vw, 576px" /></a></p>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;"># Get-View -ViewType VirtualMachine -Filter @{&#8220;Name&#8221;=&#8221;MVV30010&#8221;} | %{<br />
Get-View -ViewType VirtualMachine | %{<br />
if($_.Config.Hardware.Device | where{$_.gettype().Name -eq &#8220;VirtualSerialPort&#8221;}){<br />
$_.Name<br />
}<br />
}</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/01/29/dvswitch-scripting-part-6-private-vlan/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>dvSwitch scripting – Part 5 – Clone/pg to dvPG</title>
		<link>https://www.lucd.info/2010/01/06/dvswitch-scripting-part-5-clonepg-to-dvpg/</link>
					<comments>https://www.lucd.info/2010/01/06/dvswitch-scripting-part-5-clonepg-to-dvpg/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Wed, 06 Jan 2010 20:37:44 +0000</pubDate>
				<category><![CDATA[dvSwitch]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[clone]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=1498</guid>

					<description><![CDATA[An interesting question came up in the PowerCLI Community recently. Jason wanted to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>An<a href="https://communities.vmware.com/message/1451414#1451414" target="_blank"> interesting question</a> came up in the PowerCLI Community recently.<strong> Jason</strong> wanted to use a script from <a href="https://communities.vmware.com/message/1298627#1298627" target="_blank">another thread</a> where you could connect a NIC to a specific <strong>portgroup</strong> while <strong>cloning</strong> a new guest from a template.</p>
<p>The script didn&#8217;t work when the requested portgroup was on a dvSwitch. Enough of a reason for me to have another look.</p>
<p><span id="more-1498"></span>The original script looks up the portgroup on the ESX server and then just copies the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.device.VirtualDevice.html" target="_blank">VirtualDevice</a> object to the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.vm.ConfigSpec.html" target="_blank">VirtualMachineConfigSpec</a> object.</p>
<p>But, as expected this didn&#8217;t seem to work when dealing with dvSwitch portgroups.</p>
<p>In fact, to my amazement, the script created a new portgroup with the same name as the requested dvSwitch portgroup. No error message whatsoever !</p>
<p>The following script solves the problem. It finds the dvSwitch, the portgroup and sets up the configuration parameters correctly for the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualMachine.html#clone" target="_blank">CloneVM_Task</a> method.</p>
<p>The template was created with a connection to a regular portgroup.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/01/clone-template-pg.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1503" title="clone-template-pg" src="https://lucd.info/wp-content/uploads/2010/01/clone-template-pg.png" alt="" width="372" height="305" srcset="https://www.lucd.info/wp-content/uploads/2010/01/clone-template-pg.png 372w, https://www.lucd.info/wp-content/uploads/2010/01/clone-template-pg-300x245.png 300w" sizes="auto, (max-width: 372px) 100vw, 372px" /></a></p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$templateName = &lt;templateName&gt;
$newVM = &lt;vmName&gt;
$esxName = &lt;tgt-esxName&gt;
$poolName = &lt;tgt-poolName&gt;
$folderName = &lt;tgt-folderName&gt;
$datastoreName = &lt;tgt-datastoreName&gt;

$nicName = &quot;Network adapter 1&quot;
$dvPG = &quot;dvPG1&quot;

$fromVM = Get-View -Id (Get-Template $templateName).Id
$folder = Get-Folder $folderName | Get-View

# Find the dvSwitch &amp; dvPortGroup
$esx = Get-View -Id $fromVM.Runtime.Host
foreach($netMoRef in $esx.Network){
	if($netMoRef.Type -eq &quot;DistributedVirtualPortGroup&quot;){
		$net = Get-View -Id $netMoRef
		if($net.Name -eq $dvPg){
			$dvPGKey = $net.MoRef.Value
			$dvSwitchUuid = (Get-View -Id $net.Config.DistributedVirtualSwitch).Summary.Uuid
		}
	}
}

# Find the NIC
foreach($tempdev in $fromVM.Config.Hardware.Device){
	if($tempdev.DeviceInfo.Label -eq $nicName){
		$tgtdev = $tempdev
	}
}

$spec = New-Object VMware.Vim.VirtualMachineCloneSpec
$spec.Config = New-Object VMware.Vim.VirtualMachineConfigSpec

$devSpec = New-Object VMware.Vim.VirtualDeviceConfigSpec

$dev = New-Object (&quot;VMware.Vim.&quot; + $tgtdev.GetType().Name)
$dev.deviceInfo = New-Object VMware.Vim.Description
$dev.deviceInfo.label = $tgtdev.DeviceInfo.Label
$dev.deviceInfo.summary = $tgtdev.DeviceInfo.Summary
$dev.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
$dev.Backing.Port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection
$dev.Backing.Port.PortgroupKey = $dvPGKey
$dev.Backing.Port.SwitchUuid = $dvSwitchUuid
$dev.Key = $tgtdev.Key

$devSpec.Device = $dev
$devSpec.Operation = &quot;edit&quot;

$spec.Config.deviceChange += $devSpec

$spec.location = New-Object VMware.Vim.VirtualMachineRelocateSpec
$spec.location.datastore = (Get-Datastore $datastoreName | Get-View).MoRef
$spec.location.host = (Get-VMHost $esxName | Get-View).MoRef
$spec.Location.Pool = (Get-ResourcePool $poolName | Get-View).MoRef
$spec.powerOn = $false
$spec.template = $false

$fromVM.CloneVM_Task($folder.MoRef, $newVM, $spec)</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 15</strong>: The script uses the template&#8217;s ESX host to find the dvSwitch</p>
<p><strong>Line 20,21</strong>: To specify the dvSwitch we need the Uuid and the key of the dvSwitch</p>
<p><strong>Line 27-31</strong>: This loop finds the NIC which we want to connect to the dvSwitch portgroup. The script doesn&#8217;t have any error handling code for this. If the NIC name is misspelled, the CloneVM_Task will fail.</p>
<p><strong>Line 42,43</strong>: The backing device is where the big difference with the original script is located.</p>
<p>After the script runs you will see your new guest, called PC1 in my test environment, connected to the dvSwitch portgroup.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/01/clone-after.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1502" title="clone-after" src="https://lucd.info/wp-content/uploads/2010/01/clone-after.png" alt="" width="460" height="190" srcset="https://www.lucd.info/wp-content/uploads/2010/01/clone-after.png 575w, https://www.lucd.info/wp-content/uploads/2010/01/clone-after-300x123.png 300w" sizes="auto, (max-width: 460px) 100vw, 460px" /></a></p>
<p>So with this script you don&#8217;t have go updating your huge collection of templates when you move to dvSwitches <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/01/06/dvswitch-scripting-part-5-clonepg-to-dvpg/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
