<?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>New-VIProperty Archives - LucD notes</title>
	<atom:link href="https://www.lucd.info/tag/new-viproperty/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.lucd.info/tag/new-viproperty/</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Wed, 12 Aug 2020 17:24:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.10</generator>

<image>
	<url>https://www.lucd.info/wp-content/uploads/2018/12/cropped-120px-Tibetan_Dharmacakra-32x32.png</url>
	<title>New-VIProperty Archives - LucD notes</title>
	<link>https://www.lucd.info/tag/new-viproperty/</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>Folder by Path</title>
		<link>https://www.lucd.info/2012/05/18/folder-by-path/</link>
					<comments>https://www.lucd.info/2012/05/18/folder-by-path/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Fri, 18 May 2012 21:36:37 +0000</pubDate>
				<category><![CDATA[Folder]]></category>
		<category><![CDATA[New-VIProperty]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Path]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=4027</guid>

					<description><![CDATA[There seem to be many vSphere environments where the same foldername is used [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>There seem to be many vSphere environments where the same foldername is used multiple times. A blue folder with the name <strong>Servers</strong> is quite common for example.</p>
<p><img fetchpriority="high" decoding="async" class="alignnone wp-image-4032" style="margin-left: 25px; margin-right: 25px;" title="FolderByPath1" src="https://lucd.info/wp-content/uploads/2012/05/FolderByPath1.png" alt="" width="250" height="250" srcset="https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath1.png 313w, https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath1-150x150.png 150w, https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath1-300x300.png 300w" sizes="(max-width: 250px) 100vw, 250px" /></p>
<p>If you need to retrieve such a folder with the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-Folder.html" target="_blank" rel="noopener noreferrer">Get-Folder</a> cmdlet, you will have to walk the path to the folder leaf by leaf and use the <strong>Location</strong> parameter. It would be handier if you could just specify the <strong>path</strong> to the folder and retrieve the folder like that.</p>
<p>The following is a small function that will allow you to do just that.</p>
<p><strong><span style="background-color: #ffff00;">Update August 6th 2020</span></strong>: The missing NoRecursion switch caused folders by the same name, further down in the hierarchy, to be returned as well.</p>
<p><strong><span style="background-color: #ffff00;">Update July 5th 2019</span></strong>: The functions have been updated to support the situation where a user is connected to multiple vSphere Servers.</p>
<p><strong><span style="background-color: #ffff00;">Update February 18th 2016</span></strong>: In some situations the function might return folders with the same name from different location. Fixed by adding <strong>NoRecursion</strong> on line 48<br />
<span id="more-4027"></span></p>
<h2>The Script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-FolderByPath{
&lt;#
 .SYNOPSIS Retrieve folders by giving a path
 .DESCRIPTION The function will retrieve a folder by it's path.
   The path can contain any type of leave (folder or datacenter).
 .NOTES
   Author: Luc Dekens .PARAMETER Path The path to the folder. This is a required parameter.
 .PARAMETER
   Path The path to the folder. This is a required parameter.
 .PARAMETER
   Separator The character that is used to separate the leaves in the path. The default is '/'
 .EXAMPLE
   PS&gt; Get-FolderByPath -Path "Folder1/Datacenter/Folder2"
 .EXAMPLE
   PS&gt; Get-FolderByPath -Path "Folder1&gt;Folder2" -Separator '&gt;'
#&gt;
 
  param(
  [CmdletBinding()]
  [parameter(Mandatory = $true)]
  [System.String[]]${Path},
  [char]${Separator} = '/'
  )
 
  process{
    if((Get-PowerCLIConfiguration).DefaultVIServerMode -eq "Multiple"){
      $vcs = $global:defaultVIServers
    }
    else{
      $vcs = $global:defaultVIServers[0]
    }
    $folders = @()
 
    foreach($vc in $vcs){
      $si = Get-View ServiceInstance -Server $vc
      $rootName = (Get-View -Id $si.Content.RootFolder -Property Name).Name
      foreach($strPath in $Path){
        $root = Get-Folder -Name $rootName -Server $vc -ErrorAction SilentlyContinue
        $strPath.Split($Separator) | %{
          $root = Get-Inventory -Name $_ -Location $root -NoRecursion -Server $vc -ErrorAction SilentlyContinue
          if((Get-Inventory -Location $root -NoRecursion | Select -ExpandProperty Name) -contains "vm"){
            $root = Get-Inventory -Name "vm" -Location $root -Server $vc -NoRecursion
          }
        }
        $root | where {$_ -is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]}|%{
          $folders += Get-Folder -Name $_.Name -Location $root.Parent -NoRecursion -Server $vc
        }
      }
    }
    $folders
  }
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 26-33</strong>: Handle multiple vSphere Server connections</p>
<p><strong>Line 26</strong>: Takes care of Single or Multiple mode. In multiple mode, the function will look for the folder on each connected vSphere server. See <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-PowerCLIConfiguration.html" target="_blank" rel="noopener noreferrer">Get-PowerCLIConfiguration</a>.</p>
<p><strong>Line 33</strong>: Loop over all the vSphere servers.</p>
<p><strong>Line 34-35</strong>: Get the rootfolder (aka folder Datacenters) for a specific vSphere server connection</p>
<p><strong>Line 36</strong>: The function can accept more than one path. This loops through all the provided paths.</p>
<p><strong>Line 37</strong>: The function starts looking at the root folder. This is the hidden <strong><em>Datacenters</em></strong> folder.</p>
<p><strong>Line 38</strong>: The provided path is split into separate leaves.</p>
<p><strong>Line 39</strong>: The Path can have a datacenter as a leaf, hence the functions uses the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-Inventory.html" target="_blank" rel="noopener noreferrer">Get-Inventory</a> cmdlet to find the children.</p>
<p><strong>Line 40-42</strong>: Skip the hidden &#8220;vm&#8221; folder</p>
<p><strong>Line 44-46</strong>: When all the children are retrieved, the <strong>Where</strong>-clause will only pass the <strong>Folder</strong> objects back.</p>
<p><strong>Line 45</strong>: Notice that we have to back one leaf, hence the <strong>$root.Parent</strong> on the Location parameter.</p>
<h2>Sample Usage</h2>
<p>I created the function to avoid this problem.</p>
<p><img decoding="async" class="alignnone wp-image-4034" style="margin-left: 25px; margin-right: 25px;" title="FolderByPath2" src="https://lucd.info/wp-content/uploads/2012/05/FolderByPath2.png" alt="" width="363" height="98" srcset="https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath2.png 454w, https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath2-300x80.png 300w" sizes="(max-width: 363px) 100vw, 363px" /></p>
<p>The function is quite simple to use.</p><pre class="urvanov-syntax-highlighter-plain-tag">Get-FolderByPath -Path "DC1/Blue1/Blue12/Blue121/Servers"</pre><p>This gives me exactly the folder I want.</p>
<p><img decoding="async" class="alignnone wp-image-4035" style="margin-left: 25px; margin-right: 25px;" title="FolderByPath3" src="https://lucd.info/wp-content/uploads/2012/05/FolderByPath3.png" alt="" width="461" height="90" srcset="https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath3.png 576w, https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath3-300x58.png 300w" sizes="(max-width: 461px) 100vw, 461px" /></p>
<p>Now it becomes easy to fetch for example all the VMs that are located in a specific folder.</p><pre class="urvanov-syntax-highlighter-plain-tag">Get-FolderByPath -Path "DC1/Blue1/Blue12/Blue121/Servers" | Get-VM</pre><p><img loading="lazy" decoding="async" class="alignnone wp-image-4036" style="margin-left: 25px; margin-right: 25px;" title="FolderByPath4" src="https://lucd.info/wp-content/uploads/2012/05/FolderByPath4.png" alt="" width="534" height="82" srcset="https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath4.png 668w, https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath4-300x45.png 300w" sizes="auto, (max-width: 534px) 100vw, 534px" /></p>
<h2>Bonus: a New-VIProperty</h2>
<p>Retrieving folders by path became easy, it would now be interesting to see what the path of a VM is. That&#8217;s where you can use the following <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/New-VIProperty.html" target="_blank" rel="noopener noreferrer">New-VIProperty</a>.</p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name 'BlueFolderPath' -ObjectType 'VirtualMachine' -Value {
    param($vm)

    function Get-ParentName{
        param($object)

        if($object.Folder){
            $blue = Get-ParentName $object.Folder
            $name = $object.Folder.Name
        }
        elseif($object.Parent -and $object.Parent.GetType().Name -like "Folder*"){
            $blue = Get-ParentName $object.Parent
            $name = $object.Parent.Name
        }
        elseif($object.ParentFolder){
            $blue = Get-ParentName $object.ParentFolder
            $name = $object.ParentFolder.Name
        }
        if("vm","Datacenters" -notcontains $name){
            $blue + "/" + $name
        }
        else{
            $blue
        }
    }

    (Get-ParentName $vm).Remove(0,1)
} -Force | Out-Null</pre><p>It creates a new property called <strong>BlueFolderPath</strong> and that property will show you the blue folder path where a VM is located.</p><pre class="urvanov-syntax-highlighter-plain-tag">Get-FolderByPath -Path "DC1/Blue1/Blue12/Blue121/Servers" | Get-VM |
Select Name,BlueFolderPath</pre><p><img loading="lazy" decoding="async" class="alignnone wp-image-4037" style="margin-left: 25px; margin-right: 25px;" title="FolderByPath5" src="https://lucd.info/wp-content/uploads/2012/05/FolderByPath5.png" alt="" width="560" height="107" srcset="https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath5.png 700w, https://www.lucd.info/wp-content/uploads/2012/05/FolderByPath5-300x57.png 300w" sizes="auto, (max-width: 560px) 100vw, 560px" /></p><pre class="urvanov-syntax-highlighter-plain-tag">Enjoy!</pre><p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2012/05/18/folder-by-path/feed/</wfw:commentRss>
			<slash:comments>52</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>VIProperties in a Module</title>
		<link>https://www.lucd.info/2011/08/17/viproperties-in-a-module/</link>
					<comments>https://www.lucd.info/2011/08/17/viproperties-in-a-module/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Wed, 17 Aug 2011 19:50:11 +0000</pubDate>
				<category><![CDATA[New-VIProperty]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[100th]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3537</guid>

					<description><![CDATA[Judging from the number of hits, the VIProperties page seems to be rather [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Judging from the number of hits, the <a href="https://www.lucd.info/viproperties/" target="_blank" rel="noopener noreferrer">VIProperties</a> page seems to be rather popular.<br />
The number of entries on that page increases nearly on a daily basis.And judging by the list of people who submitted <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/New-VIProperty.html" target="_blank" rel="noopener noreferrer">New-VIProperty</a> entries, this particular feature of <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview" target="_blank" rel="noopener noreferrer">PowerCLI</a> is in use all over the place.<br />
Recently my co-author of the PowerCLI book, <a href="https://twitter.com/#!/jonathanmedd" target="_blank" rel="noopener noreferrer">Jonathan Medd, </a>had a brilliant idea.</p>
<p>Why not bundle all the VIProperties in a module ? The user would just have to do an <strong>Import-Module</strong>, instead of a copy/paste on each of the entries.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/08/100th1.jpg"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3559" title="100th" src="https://lucd.info/wp-content/uploads/2011/08/100th1.jpg" alt="" width="300" height="225" /></a></p>
<p>So for the <strong>100th post</strong> on my blog I decided to bring you the <strong>VIProperty module</strong>.</p>
<p><span style="background-color: #ffff00;"><strong>Update August 25th 2011</strong></span>: added the use of the <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview" target="_blank" rel="noopener noreferrer">PowerCLI 5</a> <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI50/html/Get-VIProperty.html" target="_blank" rel="noopener noreferrer">Get-VIProperty</a> cmdlet.</p>
<p><span id="more-3537"></span></p>
<h2>Installation</h2>
<ul>
<li>Download the [wpfilebase tag=file id=4 tpl=simple]</li>
<li><strong>Unblock</strong> the ZIP file to avoid problems with your PowerShell ExecutionPolicy.</li>
</ul>
<p style="text-align: left; padding-left: 30px;"><a href="https://lucd.info/wp-content/uploads/2011/08/UnblockZip3.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3608" title="UnblockZip" src="https://lucd.info/wp-content/uploads/2011/08/UnblockZip3.png" alt="" width="298" height="409" srcset="https://www.lucd.info/wp-content/uploads/2011/08/UnblockZip3.png 373w, https://www.lucd.info/wp-content/uploads/2011/08/UnblockZip3-218x300.png 218w" sizes="auto, (max-width: 298px) 100vw, 298px" /></a></p>
<ul>
<li>Extract the files from the ZIP file. This will create a folder called <strong>VIProperty</strong>, with 2 files in there.</li>
</ul>
<ul>
<li>Copy the complete <strong>VIProperty</strong> folder to one of your <strong>Modules</strong> folders.</li>
<ul>
<li>You can check which are the Modules folders on your system like this</li>
</ul>
</ul>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$env:PSModulePath</pre><p></p>
<p><a href="https://lucd.info/wp-content/uploads/2011/08/PSModulePath.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3549" title="PSModulePath" src="https://lucd.info/wp-content/uploads/2011/08/PSModulePath.png" alt="" width="818" height="55" srcset="https://www.lucd.info/wp-content/uploads/2011/08/PSModulePath.png 818w, https://www.lucd.info/wp-content/uploads/2011/08/PSModulePath-300x20.png 300w" sizes="auto, (max-width: 818px) 100vw, 818px" /></a></p>
<h2>Usage</h2>
<p>In you PowerCLI session you can load the <strong>VIProperty</strong> module at any time with the <strong>Import-Module</strong> cmdlet.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Import-Module -Name VIProperty</pre><p></p>
<p>Since the VIProperty module doesn&#8217;t introduce functions, you can&#8217;t use the Get-Command cmdlet to see what is in the VIProperty module. But <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview" target="_blank" rel="noopener noreferrer">PowerCLI 5</a> introduced the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI50/html/Get-VIProperty.html" target="_blank" rel="noopener noreferrer">Get-VIPropery</a> cmdlet that can help.</p>
<p>When you do</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VIProperty</pre><p></p>
<p>it will return a list like this</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/08/GetVIProperty.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3611" title="GetVIProperty" src="https://lucd.info/wp-content/uploads/2011/08/GetVIProperty.png" alt="" width="569" height="378" srcset="https://www.lucd.info/wp-content/uploads/2011/08/GetVIProperty.png 813w, https://www.lucd.info/wp-content/uploads/2011/08/GetVIProperty-300x199.png 300w" sizes="auto, (max-width: 569px) 100vw, 569px" /></a></p>
<p>To remove the <strong>VIProperty</strong> module you can do</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Remove-Module -Name VIProperty</pre><p></p>
<p>but this will <strong><span style="background-color: #ffff00;">not</span></strong> remove the New-VIProperty definitions.<br />
To actually remove the New-VIProperty definitions, you can do</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Remove-VIProperty -Name * -ObjectType *</pre><p></p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2011/08/17/viproperties-in-a-module/feed/</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
		<item>
		<title>The making of a New-VIProperty called lunID</title>
		<link>https://www.lucd.info/2011/07/26/the-making-of-a-new-viproperty-called-lunid/</link>
					<comments>https://www.lucd.info/2011/07/26/the-making-of-a-new-viproperty-called-lunid/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Tue, 26 Jul 2011 08:15:21 +0000</pubDate>
				<category><![CDATA[LUN]]></category>
		<category><![CDATA[New-VIProperty]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3452</guid>

					<description><![CDATA[An interesting question arrived in my mailbox this morning. Robert wanted to know [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>An interesting question arrived in my mailbox this morning. <strong>Robert</strong> wanted to know what was the most efficient way to create a new property, called <strong>lunID</strong>,  for the objects returned by the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-ScsiLun.html" target="_blank">Get-ScsiLun</a> cmdlet.</p>
<p>The new property had to show the lunID, as it is returned in the <strong>LUN</strong> column in the vSphere client.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/07/lunID.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3453" title="lunID" src="https://lucd.info/wp-content/uploads/2011/07/lunID.png" alt="" width="586" height="119" srcset="https://www.lucd.info/wp-content/uploads/2011/07/lunID.png 586w, https://www.lucd.info/wp-content/uploads/2011/07/lunID-300x60.png 300w" sizes="auto, (max-width: 586px) 100vw, 586px" /></a></p>
<p><span id="more-3452"></span></p>
<h2>Getting there</h2>
<p>There are of course multiple ways for getting at the lunID (aren&#8217;t there always <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>After a quick look at the properties of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-ScsiLun.html" target="_blank">Get-ScsiLun</a> cmdlet, I concluded that the most obvious way to get there, was to use the <strong>RunTimeName</strong> property.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/07/RunTimeName2.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3477" title="RunTimeName" src="https://lucd.info/wp-content/uploads/2011/07/RunTimeName2.png" alt="" width="697" height="238" srcset="https://www.lucd.info/wp-content/uploads/2011/07/RunTimeName2.png 871w, https://www.lucd.info/wp-content/uploads/2011/07/RunTimeName2-300x102.png 300w" sizes="auto, (max-width: 697px) 100vw, 697px" /></a></p>
<p>The trick would be to extract the lunID from the string in a general and fast way.</p>
<p>Luckily PowerShell allows one to use RegEx expressions to do just that. With the Select-String cmdlet I should be able to extract the lunID. A quick test, showed that it was quiet easy.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$testString = &quot;vmhba0:C2:T0:L11&quot;
Select-String -InputObject $testString -Pattern &quot;\:L(\d+)$&quot; | %{
   $_.matches
}</pre><p></p>
<p>The pattern says that the cmdlet should look at the end of the string (the $ character), for a string that starts with &#8216;:L&#8217;, followed by 1 or more numeric characters. And since it are these numeric characters we are after, we ask to group them, which is indicated by the &#8216;()&#8217; in the pattern. Note that we had to escape the double colon, since it has a special meaning in a RegEx expression.</p>
<p>A test run produced the following.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/07/regex13.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3478" title="regex1" src="https://lucd.info/wp-content/uploads/2011/07/regex13.png" alt="" width="257" height="106" /></a></p>
<p>Note that the results of this RegEx operation are returned in the $matches property. To access the actual value we can use an array index, but I find using a name is easier. Luckily we can give names to a group in the RegEx expression. This gives the following script.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$testString = &quot;vmhba0:C2:T0:L11&quot;
Select-String -InputObject $testString -Pattern &quot;\:L(?&lt;lunID&gt;\d+)$&quot; | `
Select @{N=&quot;lunID&quot;;E={$_.matches[0].Groups['lunID'].Value}}</pre><p></p>
<p>Which produces this output.<br />
<a href="https://lucd.info/wp-content/uploads/2011/07/regex21.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3479" title="regex2" src="https://lucd.info/wp-content/uploads/2011/07/regex21.png" alt="" width="191" height="55" /></a></p>
<p>Everything is now in place to create our New-VIProperty definition.</p>
<h2>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name lunID -ObjectType ScsiLun -Value {
	param($lun)

	[int](Select-String &quot;:L(?&lt;lunID&gt;\d+)$&quot; `
		-InputObject $lun.RuntimeName).Matches[0].Groups['lunID'].Value
} -Force</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1</strong>: The object returned by the Get-ScsiLun cmdlet is a <strong>ScsiLun</strong> object.<br />
<strong>Line 4</strong>: The script converts the lunID to an [int] value. The RegEx expression returns all matches as a [string] by default.</p>
<h2>Trial run</h2>
<p>Let&#8217;s take the new property for a spin.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name lunID -ObjectType ScsiLun -Value {
	param($lun)

	[int](Select-String &quot;:L(?&lt;lunID&gt;\d+)$&quot; `
		-InputObject $lun.RuntimeName).Matches[0].Groups['lunID'].Value
} -Force | Out-Null

$esxName = &quot;MyHost&quot;
Get-VMHost -Name $esxName | Get-ScsiLun | `
Select CanonicalName, lunID | ft -AutoSize</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 6</strong>: The output of the New-VIProperty is thrown away by piping it to Out-Null.</p>
<p>And this produces</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/07/lunID2.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3468" title="lunID2" src="https://lucd.info/wp-content/uploads/2011/07/lunID2.png" alt="" width="357" height="186" srcset="https://www.lucd.info/wp-content/uploads/2011/07/lunID2.png 357w, https://www.lucd.info/wp-content/uploads/2011/07/lunID2-300x156.png 300w" sizes="auto, (max-width: 357px) 100vw, 357px" /></a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2011/07/26/the-making-of-a-new-viproperty-called-lunid/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Runtime Name via Extensiondata and New-VIProperty</title>
		<link>https://www.lucd.info/2010/10/17/runtime-name-via-extensiondata-and-new-viproperty/</link>
					<comments>https://www.lucd.info/2010/10/17/runtime-name-via-extensiondata-and-new-viproperty/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 17 Oct 2010 02:10:45 +0000</pubDate>
				<category><![CDATA[New-VIProperty]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[LUN]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=2706</guid>

					<description><![CDATA[One of the demos we did in our VMworld 2010 US and Europe [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>One of the demos we did in our <a href="https://www.vmworld2010.com/community/conferences/2010/" target="_blank">VMworld 2010 US</a> and <a href="https://www.vmworld2010.com/community/conferences/europe2010/" target="_blank">Europe</a> sessions, showed the use of the new <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/ExtensionData.html" target="_blank">Extensiondata</a> property and of the new <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet. Both features were introduced with <a href="https://www.vmware.com/support/developer/PowerCLI/index.html" target="_blank">PowerCLI 4.1</a>. In my <a href="https://www.lucd.info/2010/07/13/powercli-4-1-brings-the-new-viproperty-cmdlet/" target="_blank">PowerCLI 4.1 brings the New-VIProperty cmdlet</a> post I already showed the interesting possibilities this new cmdlet offers.</p>
<p>On my return from VMworld Europe there was a new thread in the <a href="https://www.vmware.com/go/powercli" target="_blank">PowerCLI Community</a> that asked how one could <a href="https://communities.vmware.com/message/1629744#1629744" target="_blank">get at the Runtime Name</a> property as it is shown in the <strong>vSphere Client</strong>. The <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-ScsiLun.html" target="_blank">Get-ScsiLun</a> and <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-ScsiLunPath.html" target="_blank">Get-ScsiLunPath</a> cmdlets unfortunately do not return that property. So I guessed it was time to show once more the strength of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet.</p>
<p><span id="more-2706"></span></p>
<h2>Intro</h2>
<p>The basic problem with the Runtime Name is the fact that this name is not available as a single property.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/10/runtime-name.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2707" title="runtime-name" src="https://lucd.info/wp-content/uploads/2010/10/runtime-name.png" alt="" width="644" height="223" srcset="https://www.lucd.info/wp-content/uploads/2010/10/runtime-name.png 644w, https://www.lucd.info/wp-content/uploads/2010/10/runtime-name-300x103.png 300w" sizes="auto, (max-width: 644px) 100vw, 644px" /></a></p>
<p>The information to compose the name, on the other hand, is available. It&#8217;s just a matter of retrieving the correct data. Via the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.HostSystem.html" target="_blank">HostSystem</a> object we can get to the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.host.StorageDeviceInfo.html" target="_blank">HostStorageDeviceInfo</a> object. Once we have this object, it&#8217;s a matter of following the correct pointers and to compose the Runtime Name.</p>
<h2>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">#requires -pssnapin VMware.VimAutomation.Core -version 4.1

function Get-ScsiLunRuntime{
&lt;#
.SYNOPSIS
  Get the Runtime Names for Scsi Luns
.DESCRIPTION
  The function returns all the ScsiLun disks present on a vSphere
	with their Canonical Name and Runtime Name
.NOTES
  Authors:	Luc Dekens
.PARAMETER VMHost
  On or more hosts for which you want to retrieve the Runtime Name
.EXAMPLE
  PS&gt; Get-ScsiLunRuntime -VMHost (Get-VMHost -Name &quot;MyEsx&quot;)
.EXAMPLE
  PS&gt; Get-VMHost -Name &quot;MyESX&quot; | Get-ScsiLunRuntime
#&gt;

	param(
	[parameter(valuefrompipeline = $true, mandatory = $true,
	HelpMessage = &quot;Enter a host&quot;)]
	[VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl[]]$VMHost,
	[switch]$Thin = $true
	)

	begin{
		$HbaNames1 = @{}
		$HbaNames2 = @{}
	}

	process{
		$VMHost | %{
			$_.ExtensionData.Config.StorageDevice.HostBusAdapter | %{
				$HbaNames1.Add($_.Key,$_.Device)
			}
			$_.ExtensionData.Config.StorageDevice.PlugStoreTopology.Adapter | %{
				$HbaNames2.Add($_.Key,$HbaNames1.Item($_.Adapter))
			}
			$_.ExtensionData.Config.StorageDevice.PlugStoreTopology.Path | %{
				$HbaNames2.Item($_.Adapter) + &quot;:C&quot; + $_.ChannelNumber + &quot;:T&quot; + $_.TargetNumber + &quot;:L&quot; + $_.LunNumber
			}
		}
	}
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1</strong>: The function requires PowerCLI 4.1</p>
<p><strong>Line 28-29</strong>: To make the retrieval easier, the script uses two hash tables to store the HBA Device Name.</p>
<p><strong>Line 34-39</strong>: Populate both hash tables.</p>
<p>The script does nothing more than display the <strong>Runtime Names</strong> for one or more ESX(i) hosts.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/10/list-runtime-names.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2712" title="list-runtime-names" src="https://lucd.info/wp-content/uploads/2010/10/list-runtime-names.png" alt="" width="216" height="95" /></a></p>
<p>The function was written to show that the Runtime Name can be composed from the information available in the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.host.StorageDeviceInfo.html" target="_blank">HostStorageDeviceInfo</a> object.</p>
<h2>Adding the property</h2>
<p>From the previous script we have a working method to compose the <strong>Runtime Name</strong>. The next step is to extend the output of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-ScsiLun.html" target="_blank">Get-ScsiLun</a> cmdlet to return the property. That&#8217;s where the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet comes into play.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name &quot;RuntimeName&quot; -ObjectType &quot;ScsiLun&quot; -Value {
	param($scsilun)

	$storDev = $scsilun.VMHost.ExtensionData.Config.StorageDevice
	$key = ($storDev.PlugStoreTopology.Device | where {$_.Lun -eq $scsilun.Key}).Key
	$stordev.PlugStoreTopology.Path | where {$_.Device -eq $key} | %{
		$device = $_
		$adapterKey = ($stordev.PlugStoreTopology.Adapter | where {$_.Key -eq $device.Adapter}).Adapter
		$adapter = ($stordev.HostBusAdapter | where {$_.Key -eq $adapterKey}).Device
		$adapter + &quot;:C&quot; + $device.ChannelNumber + &quot;:T&quot; + $device.TargetNumber + &quot;:L&quot; + $device.LunNumber
	}
} -Force</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1</strong>: All PowerCLI objects are allowed with the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet.</p>
<p><strong>Line 4</strong>: Via the <strong>VMHost </strong>property in the <strong>ScsiLunImpl</strong> object, the script has access to the complete <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.HostSystem.html" target="_blank">HostSystem</a> object. And from there it is straightforward to go to the  <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.host.StorageDeviceInfo.html" target="_blank">HostStorageDeviceInfo</a> object.</p>
<p><strong>Line 5</strong>: Via the <strong>Key</strong> property the script finds the correct LUN.</p>
<p>We can now get at the Runtime Names with the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-ScsiLun.html" target="_blank">Get-ScsiLun</a> cmdlet.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/10/Get-ScsiLun-plus.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2714" title="Get-ScsiLun-plus" src="https://lucd.info/wp-content/uploads/2010/10/Get-ScsiLun-plus.png" alt="" width="665" height="118" srcset="https://www.lucd.info/wp-content/uploads/2010/10/Get-ScsiLun-plus.png 831w, https://www.lucd.info/wp-content/uploads/2010/10/Get-ScsiLun-plus-300x53.png 300w" sizes="auto, (max-width: 665px) 100vw, 665px" /></a></p>
<p>Don&#8217;t you just love the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/10/17/runtime-name-via-extensiondata-and-new-viproperty/feed/</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>On parents and nested properties</title>
		<link>https://www.lucd.info/2010/08/01/on-parents-and-nested-properties/</link>
					<comments>https://www.lucd.info/2010/08/01/on-parents-and-nested-properties/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 01 Aug 2010 19:52:20 +0000</pubDate>
				<category><![CDATA[New-VIProperty]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=2569</guid>

					<description><![CDATA[In a recent post on the vSphere PowerCLI Blog, called New Nested Properties [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In a recent post on the <a href="https://blogs.vmware.com/vipowershell/" target="_blank">vSphere PowerCLI Blog</a>, called <a href="https://blogs.vmware.com/vipowershell/2010/07/new-nested-properties-for-navigating-to-associated-objects-in-powercli-41.html" target="_blank">New Nested Properties for Navigating to Parent Objects in PowerCLI 4.1</a>, some new features were introduced.</p>
<p>In <strong>PowerCLI 4.1</strong> some objects now have, besides the <strong>ParentId</strong> property, the <strong>actual parent object</strong> itself. This will take quite some complexity out of several scripts. This is definitely a good improvement.</p>
<p>The 2nd novelty in that post were <strong>nested properties</strong>. Some <strong>SDK object</strong> properties are now mapped directly in the <strong>PowerCLI object</strong>. For example the <strong>VMHost </strong>object now holds the <strong>StorageInfo</strong> and <strong>NetworkInfo</strong> properties besides some others. And what is even better, there is hardly any performance impact since the values will only be loaded the first time you access the properties (similar to the <strong>ExtensionData</strong> property).</p>
<p><span id="more-2569"></span></p>
<p>The selection of the SDK properties that are available this way were made by the <strong>PowerCLI Dev Team</strong> and are probably based on the most commonly used SDK object properties. But what if you want another property of the SDK object in your script ?</p>
<p>You can of course access all the properties of the SDK object through the <strong>ExtensionData</strong> property. But that comes with a performance penalty and will be visible when you run your script against a  larger vSphere environment.</p>
<p>Luckily <strong>PowerCLI 4.1</strong> also introduced the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet.</p>
<p>With that cmdlet it&#8217;s quite simple to map your selection of SDK object properties into the PowerCLI object.</p>
<p>Suppose you want to see/check the ESX(i) host&#8217;s <strong>hardware</strong> in a script. Then you can just add this line</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name 'Hardware' -ObjectType 'VMHost' `
	-ValueFromExtensionProperty 'Hardware' -Force</pre><p></p>
<p>And bingo, each object returned by Get-VMHost will now have a Hardware property.</p>
<p>Another example is the <strong><em>yellow</em></strong> folder to which a <strong>VirtualMachine</strong> belongs. In the PowerCLI object for a <strong>VirtualMachine</strong> you have a <strong>Folder</strong> property, but that points to the <strong><em>blue</em></strong> folder in which a guest is located.</p>
<p>Again the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> comes to the rescue.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name 'YellowFolderName' -ObjectType 'VirtualMachine' -Value {
	param($vm)

	$entity = Get-View $vm.ExtensionData.ResourcePool
	while($entity.GetType().Name -ne 'Folder'){
		$entity = Get-View $entity.Parent
	}
	$entity.Name
} -Force -BasedOnExtensionProperty 'ResourcePool'</pre><p></p>
<p>Heck, you can even use a recursive function. Like this:</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name 'YellowFolderName' -ObjectType 'VirtualMachine' -Value {
	param($vm)

	function Get-FirstFolder{
		param($entityMoRef)

		$entity = Get-View $entityMoRef
		while($entity.GetType().Name -ne 'Folder'){
			$entity = Get-FirstFolder $entity.Parent
		}
		$entity
	}

	(Get-FirstFolder $vm.ExtensionData.ResourcePool).Name
} -Force</pre><p></p>
<p>Don&#8217;t know how you feel, but I&#8217;m convinced of the power of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet  <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Some personal reflections</h3>
<p>With the power of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet I feel that these extra properties, that <strong>PowerCLI 4.1</strong> introduces, should have been optional or even left out by default. I know there is hardly any performance impact involved, but on the other hand they don&#8217;t make it easier for a PowerCLI newbie to grasp what is there.</p>
<p>What do you think ?</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/08/01/on-parents-and-nested-properties/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>PowerCLI 4.1 brings the New-VIProperty cmdlet</title>
		<link>https://www.lucd.info/2010/07/13/powercli-4-1-brings-the-new-viproperty-cmdlet/</link>
					<comments>https://www.lucd.info/2010/07/13/powercli-4-1-brings-the-new-viproperty-cmdlet/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Tue, 13 Jul 2010 07:55:58 +0000</pubDate>
				<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[New-VIProperty]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=2435</guid>

					<description><![CDATA[In the new PowerCLI 4.1 build 264274 there are two new cmdlets, called [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In the <a href="https://communities.vmware.com/community/vmtn/vsphere/automationtools/powercli?view=overview" target="_blank">new PowerCLI 4.1 build 264274</a> there are two new cmdlets, called <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> and <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Remove-VIProperty.html" target="_blank">Remove-VIProperty</a>, that deserve your special attention.</p>
<p>The <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet allows you to add a new properties to any PowerCLI object (InventoryItem, HostSystem, VirtualMachine&#8230;). And it&#8217;s up to you to define what the value of this new property will !</p>
<p>The <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Remove-VIProperty.html" target="_blank">Remove-VIProperty</a> cmdlet allows you to remove such a new property.</p>
<p>These new cmdlets, combined with the new <strong>Extension</strong> property, will change several of the well established ways that you use in your PowerCLI scripts. And besides adding a lot of flexibility, the extension property will make your scripts considerably faster (if used wisely).</p>
<p><span id="more-2435"></span></p>
<h2>What is an extension property?</h2>
<p>In short, it&#8217;s a <strong>new property</strong> you add to any of the PowerCLI objects. You select the <strong>name</strong> of the property and also what will be the <strong>value</strong> of the new property.</p>
<p>An example will perhaps make it clearer.</p>
<p>Let&#8217;s take the PowerCLI <strong>Datastore</strong> object. It&#8217;s returned by the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-Datastore.html" target="_blank">Get-Datastore</a> cmdlet and has the following properties.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/07/DS-object1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2444" title="DS-object" src="https://lucd.info/wp-content/uploads/2010/07/DS-object1.png" alt="" width="537" height="166" srcset="https://www.lucd.info/wp-content/uploads/2010/07/DS-object1.png 671w, https://www.lucd.info/wp-content/uploads/2010/07/DS-object1-300x92.png 300w" sizes="auto, (max-width: 537px) 100vw, 537px" /></a></p>
<p>Notice the <strong>FreeSpaceMB</strong> and <strong>CapacityMB</strong> properties, which are both giving the values in <strong>MB</strong>.</p>
<p>You are now tasked to create a report containing the name of the datastore and the free space in <strong>GB</strong>.</p>
<p>Till now you had to do something like this:</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2439" title="DS-freespaceGB1" src="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB1.png" alt="" width="704" height="59" srcset="https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB1.png 880w, https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB1-300x25.png 300w" sizes="auto, (max-width: 704px) 100vw, 704px" /></a></p>
<p>And if you wanted this in a nicer format, you could do:</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB2.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2440" title="DS-freespaceGB2" src="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB2.png" alt="" width="798" height="59" srcset="https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB2.png 998w, https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB2-300x22.png 300w" sizes="auto, (max-width: 798px) 100vw, 798px" /></a></p>
<p>But with the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet this can be done differently now.</p>
<p>First you define the new property. You specify a Name for the property, the PowerCLI object on which you want to add the new property and how the value of the new property shall be obtained/calculated.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2442" title="DS-freespaceGB-extprop" src="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop.png" alt="" width="757" height="30" srcset="https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop.png 946w, https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop-300x11.png 300w" sizes="auto, (max-width: 757px) 100vw, 757px" /></a></p>
<p>And from now on you can use the new <strong>FreeSpaceGB</strong> property for example in a <strong>Select-Object</strong> cmdlet like this.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop-select.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2443" title="DS-freespaceGB-extprop-select" src="https://lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop-select.png" alt="" width="518" height="59" srcset="https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop-select.png 648w, https://www.lucd.info/wp-content/uploads/2010/07/DS-freespaceGB-extprop-select-300x34.png 300w" sizes="auto, (max-width: 518px) 100vw, 518px" /></a></p>
<p>No more need to remember the tedious expression from before. You compose your <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet and the new property will be there each time you retrieve a Datastore object.</p>
<p><a href="https://lucd.info/wp-content/uploads/2010/07/DS-object-ext.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2445" title="DS-object-ext" src="https://lucd.info/wp-content/uploads/2010/07/DS-object-ext.png" alt="" width="533" height="186" srcset="https://www.lucd.info/wp-content/uploads/2010/07/DS-object-ext.png 666w, https://www.lucd.info/wp-content/uploads/2010/07/DS-object-ext-300x104.png 300w" sizes="auto, (max-width: 533px) 100vw, 533px" /></a></p>
<p><strong>Note </strong>that an extension property defined this way, will only exist for as long as you have your PowerCLI environment running.  If you restart your PowerCLI environment, the new property will not be there anymore.</p>
<p>If you want to have some of these new properties available each time you start your PowerCLI environment, you could for example place the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> statements in your profile.</p>
<h2>How to get a value in a new property?</h2>
<h3>Properties from the PowerCLI object.</h3>
<p>In the previous example we populated the new property with a recalculated value of an existing property of the PowerCLI object. But there are other ways of setting the value of a new property.</p>
<p>In the sample script I used the <strong>$args[0]</strong> variable to refer to the PowerCLI object itself. You can also define the current PowerCLI object with the <strong>param</strong> statement.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name FreeSpaceGB -ObjectType Datastore -Value {
	&quot;{0:f1}&quot; -f ($Args[0].FreeSpaceMB/1KB)
}</pre><p></p>
<p>is equivalent to</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name FreeSpaceGB -ObjectType Datastore -Value {
	param($ds)

	&quot;{0:f1}&quot; -f ($ds.FreeSpaceMB/1KB)
}</pre><p></p>
<h3>Properties from the API object.</h3>
<p>Suppose we are asked to provide per datastore how many guests are stored on that datastore. As always with PowerShell/PowerCLI there are many ways of doing this, but in this case we are going for the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> cmdlet.</p>
<p>In the API <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.Datastore.html" target="_blank">Datastore</a> object there is a property, called <strong>VM</strong>, that holds a <strong>MoRef</strong> to each guests stored on that datastore. If we count the number of entries in this property, we will have the number of guests.</p>
<p>In the <a href="https://communities.vmware.com/community/vmtn/vsphere/automationtools/powercli?view=overview" target="_blank">latest PowerCLI build</a> the complete API object is accessible under the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/ExtensionData.html" target="_blank">ExtensionData</a> propery. That will allow us to do something like this.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name VMcount -ObjectType Datastore -Value {
	param($ds)

	$ds.ExtensionData.Vm.Count
}</pre><p></p>
<p>Great, we now have access to the complete <strong>API object</strong>. No more need to do a <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-View.html" target="_blank">Get-View</a> everytime we need the <strong>API object</strong>.<br />
But the tradeoff is that the mapping of the <strong>API object</strong> takes resources.</p>
<p>Your scripts will run longer when the API object has to be fetched and mapped each time a <strong>PowerCLI object</strong> is fetched.<br />
Luckily the <strong>PowerCLI Dev Team</strong> came up with a great solution!<br />
The ExtensionData property will only map to the API object when you <span style="text-decoration: underline;"><strong>access</strong></span> the property or any of the subproperties.<br />
And to make it even more optimal, the <strong>Dev Team</strong> introduced the <strong>-BasedOnExtensionProperty</strong> parameter.</p>
<p>This parameter allows you to specify which specific properties of the API object you are going to use in the <strong>-Value</strong> script block.</p>
<p>That way access can even be more optimised. In our sample this would become.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name VMcount -ObjectType Datastore -Value {
	param($ds)

	$ds.ExtensionData.Vm.Count
} -BasedOnExtensionProperty 'vm'</pre><p></p>
<p>When you now run the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Get-Datastore.html" target="_blank">Get-Datastore</a> cmdlet against a fair number of datastores, you will notice that the execution time will have improved dramatically.</p>
<h3>Properties from the API object with aggregation functions.</h3>
<p>Quite often the actions you have to take for the <strong>-Value</strong> parameter are simple one-to-one <strong>mappings</strong> or any of the following <strong>aggregation</strong> functions: SUM, AVERAGE or AVG, MIN, MAX, UNIQUE, COUNT.</p>
<p>With the <strong>-ValueFromExtensionProperty</strong> parameter you can use a simple mapping or one of the aggregation functions without setting up a complete script block.<br />
Our example would become</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">New-VIProperty -Name VMcount -ObjectType Datastore -ValueFromExtensionProperty 'COUNT vm'</pre><p></p>
<p>This concludes my short review of the <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/New-VIProperty.html" target="_blank">New-VIProperty</a> and <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Remove-VIProperty.html" target="_blank">Remove-VIProperty</a> cmdlets.</p>
<p>Play around with these new cmdlets and feel free to post some of the amazing use cases you will no doubt come up with.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2010/07/13/powercli-4-1-brings-the-new-viproperty-cmdlet/feed/</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
			</item>
	</channel>
</rss>
