<?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>VIObject Archives - LucD notes</title>
	<atom:link href="https://www.lucd.info/tag/viobject/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.lucd.info/tag/viobject/</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Wed, 08 Apr 2020 11:04:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://www.lucd.info/wp-content/uploads/2018/12/cropped-120px-Tibetan_Dharmacakra-32x32.png</url>
	<title>VIObject Archives - LucD notes</title>
	<link>https://www.lucd.info/tag/viobject/</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>vSphere Object by Path</title>
		<link>https://www.lucd.info/2016/06/03/vsphere-object-path/</link>
					<comments>https://www.lucd.info/2016/06/03/vsphere-object-path/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Fri, 03 Jun 2016 16:49:00 +0000</pubDate>
				<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[Path]]></category>
		<category><![CDATA[VIObject]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=5247</guid>

					<description><![CDATA[In an older post, named Folder by Path, I provided a function to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In an older post, named <a href="https://www.lucd.info/2012/05/18/folder-by-path/" target="_blank" rel="noopener noreferrer">Folder by Path</a>, I provided a function to retrieve a Folder object by it&#8217;s path.</p>
<p>With the recent publication of my <a href="https://www.lucd.info/2016/06/03/get-inventoryplus-inventory-all-vsphere-objects/" target="_blank" rel="noopener noreferrer">Get-InventoryPlus</a> function, I can now get the path to all vSphere objects. So the obvious next step was to create a function, that would be able to use that information and retrieve <strong>any</strong> vSphere object by it&#8217;s <strong>path</strong>.</p>
<p style="padding-left: 30px;"><a href="https://www.lucd.info/2016/06/03/vsphere-object-path/img_20160602_084338/" rel="attachment wp-att-5249"><img fetchpriority="high" decoding="async" class="alignnone wp-image-5249 size-medium" src="https://lucd.info/wp-content/uploads/2016/06/IMG_20160602_084338-300x225.jpg" alt="IMG_20160602_084338" width="300" height="225" srcset="https://www.lucd.info/wp-content/uploads/2016/06/IMG_20160602_084338-300x225.jpg 300w, https://www.lucd.info/wp-content/uploads/2016/06/IMG_20160602_084338-768x576.jpg 768w, https://www.lucd.info/wp-content/uploads/2016/06/IMG_20160602_084338-1024x768.jpg 1024w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>The function was first demonstrated during the <a href="http://www.vmug.be/abstracts-24th-vmug-2nd-june-2016/" target="_blank" rel="noopener noreferrer">24th VMUGBe</a> in Mechelen.</p>
<p><span id="more-5247"></span></p>
<h2>The Script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-VIObjectByPath{
&lt;#
.SYNOPSIS
  Retrieve a vSphere object by it's path.
.DESCRIPTION
  This function will retrieve a vSphere object from it's path.
  The path can be absolute or relative.
  When a relative path is provided, the StartNode needs
  to be provided
.NOTES
  Author:  Luc Dekens
.PARAMETER StartNode
  The vSphere Server (vCenter or ESXi) from which to retrieve
  the objects.
  The default is $Global:DefaultVIServer
.PARAMETER Path
  A string with the absolute or relative path.
  The path shall not contain any hidden folders.
.EXAMPLE
  PS&gt; Get-VIObjectByPath -Path '/Datacenter/Folder/VM1'
.EXAMPLE
  PS&gt; Get-InventoryPlus -StartNode $node -Path $path
#&gt;

  param(
    [VMware.Vim.ManagedEntity]$StartNode = (
      Get-View -Id (Get-View -Id ServiceInstance).Content.RootFolder
    ),
    [String]$Path
  )

  function Get-NodeChild{
    param(
      [VMware.Vim.ManagedEntity]$Node
    )
  
    $hidden = 'vm','host','network','datastore','Resources'
    switch($Node){
      {$_ -is [VMware.Vim.Folder]}{
        if($Node.ChildEntity){
          Get-View -Id $Node.ChildEntity
        }
      }
      {$_ -is [VMware.Vim.Datacenter]}{
        $all = @()
        $all += Get-View -Id $Node.VmFolder
        $all += Get-View -Id $Node.HostFolder
        $all += Get-View -Id $Node.DatastoreFolder
        $all += Get-View -Id $Node.NetworkFolder
        $all | %{
          if($hidden -contains $_.Name){
            Get-NodeChild -Node $_
          }
          else{
            $_
          }
        }
      }
      {$_ -is [VMware.Vim.ClusterComputeResource]}{
        $all = @()
        $all += Get-View -Id $Node.Host
        $all += Get-View -Id $Node.ResourcePool 
        $all = $all | %{
          if($hidden -contains $_.Name){
            Get-NodeChild -Node $_
          }
          else{
            $_
          }
        }
        $all
      }
      {$_ -is [VMware.Vim.ResourcePool]}{
        $all = @()
        if($Node.ResourcePool){
          $all += Get-View -Id $Node.ResourcePool
        }
        if($Node.vm){
          $all += Get-View -Id $Node.vm
        }
        $all
      }
      {$_ -is [VMware.Vim.DistributedVirtualSwitch]}{
        Get-View -Id $Node.Portgroup
      }
    }
  }

  $found = $true

  # Loop through Path
  $node = $StartNode
  foreach($qualifier in $Path.TrimStart('/').Split('/',[StringSplitOptions]::RemoveEmptyEntries)){
    $nodeMatch = @($node) | %{
      Get-NodeChild -Node $_ | where{$_.Name -eq $qualifier}
    }
    if(!$nodeMatch){
      $found = $false
      $node = $null
      break
    }
    $node = $nodeMatch
  }

  New-Object PSObject -Property @{
    Path = $Path
    Found = $found
    Node = $node
  }
}</pre><p></p>
<h3>Annotations</h3>
<p><strong>Line 26-28</strong>: The default StartNode is the RootFolder of the default vSphere server ($Global:DefaultVIServer)</p>
<p><strong>Line 32-87</strong>: A inline Helper function that will return all children of a node. When a of the childnode is one of the hidden folders, the helper calls itself recursively. This to avoid returning one of the hidden folders.</p>
<p><strong>Line 38</strong>: Depending on the Type of the node, different properties need to be used to find the children of a node.</p>
<p><strong>Line 46-48</strong>: A Datacenter node points to four hidden folders. Each of these hidden folders in turn points to a number of other objects of a specific type.</p>
<p><strong>Line 93</strong>: To avoid that the Split method returns an empty object when the Path is just the root (/), the [StringSplitOptions]::RemoveEmptyEntries option needs to be used.</p>
<p><strong>Line 105-109</strong>: The result is returned as a custom object. The properties of this custom object allows easy access to the results: was the node found, what was the path and what is the actual VIObject.</p>
<h2>Sample Usage</h2>
<h3>Simple</h3>
<p>In it&#8217;s simplest form, you just provide a path with the Path parameter.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VIObjectByPath -Path '/Folder11'</pre><p></p>
<p><a href="https://www.lucd.info/2016/06/03/vsphere-object-path/path-1/" rel="attachment wp-att-5258"><img decoding="async" class="alignnone size-full wp-image-5258" src="https://lucd.info/wp-content/uploads/2016/06/path-1.jpg" alt="path-1" width="442" height="95" srcset="https://www.lucd.info/wp-content/uploads/2016/06/path-1.jpg 442w, https://www.lucd.info/wp-content/uploads/2016/06/path-1-300x64.jpg 300w" sizes="(max-width: 442px) 100vw, 442px" /></a></p>
<p>The result is an object with a number of properties:</p>
<ul>
<li>Path: the path that was passed into the function</li>
<li>Found: a Boolean, indicating if the node was found</li>
<li>Node: the actual vSphere object</li>
</ul>
<h3>Inventory Check</h3>
<p>We can use the output of the <a href="https://www.lucd.info/2016/06/03/get-inventoryplus-inventory-all-vsphere-objects/" target="_blank" rel="noopener noreferrer">Get-InventoryPlus</a> function, record the result, and then check if all the vSphere objects that were reported are still there. Kind of an <strong>iCheck</strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f606.png" alt="😆" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The inventory was created with the following lines</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-VIObjectByPath -NoValue 'na' | 
Export-Csv -Path c:\Temp\inventory.csv -NoTypeInformation -UseCulture</pre><p></p>
<p>The resulting CSV file looks something like this</p>
<p><a href="https://www.lucd.info/2016/06/03/vsphere-object-path/path-2/" rel="attachment wp-att-5259"><img decoding="async" class="alignnone wp-image-5259 size-medium" src="https://lucd.info/wp-content/uploads/2016/06/path-2-300x220.jpg" alt="path-2" width="300" height="220" srcset="https://www.lucd.info/wp-content/uploads/2016/06/path-2-300x220.jpg 300w, https://www.lucd.info/wp-content/uploads/2016/06/path-2.jpg 454w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>The following script will read the inventory, and use the Get-VIObjectByPath function to check if each of the nodes in the inventory is still there.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Test-NodePath{
  param(
    [String]$Path
  )

  $nodeObj = Get-VIObjectByPath -Path $Path
  if($nodeObj.Found){$true}else{$false}
}

foreach($entry in (Import-Csv C:\Temp\inventory.csv -UseCulture)){
  $path = $entry.Path

  Write-Host &quot;$($Entry.Type) $($entry.Name)&quot;

  if($entry.Path -ne 'na'){
    Write-Host -ForegroundColor Yellow &quot;`tPath &quot; -NoNewline
    Write-Host &quot;$($Entry.Path)&quot; -NoNewline

    if(Test-NodePath -Path $entry.Path){
      Write-Host -ForegroundColor Green &quot;`tok&quot;
    }
    else{
      Write-Host -ForegroundColor Yellow &quot;`tnok&quot;
    }
  }

  if($entry.BluePath -ne 'na'){
    Write-Host -ForegroundColor Cyan &quot;`tBluePath &quot; -NoNewline
    Write-Host &quot;$($Entry.BluePath)&quot; -NoNewline

    if(Test-NodePath -StartNode $rootFolder -Path $entry.BluePath){
      Write-Host -ForegroundColor Green &quot;`tok&quot;
    }
    else{
      Write-Host -ForegroundColor Yellow &quot;`tnok&quot;
    }
  }
}</pre><p></p>
<p>The result is displayed on the PS console (yes, I know this must have killed a lot of puppies), and looks like this.</p>
<p><a href="https://www.lucd.info/2016/06/03/vsphere-object-path/path-3/" rel="attachment wp-att-5260"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5260" src="https://lucd.info/wp-content/uploads/2016/06/path-3.jpg" alt="path-3" width="542" height="320" srcset="https://www.lucd.info/wp-content/uploads/2016/06/path-3.jpg 542w, https://www.lucd.info/wp-content/uploads/2016/06/path-3-300x177.jpg 300w" sizes="auto, (max-width: 542px) 100vw, 542px" /></a></p>
<p>Looks like the junior admin removed a VM !</p>
<p>&nbsp;</p>
<p>Enjoy!</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2016/06/03/vsphere-object-path/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
