<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>LucD notes</title>
	
	<link>http://www.lucd.info</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Sun, 29 Jan 2012 19:03:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/LucdNotes" /><feedburner:info uri="lucdnotes" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Variations on a port</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/rV72EKYnFhM/</link>
		<comments>http://www.lucd.info/2012/01/29/variations-on-a-port/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 16:34:11 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<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 Reference book. He was looking for a method to find the port used by a VM when connected to a portgroup on a dvSwitch. Finding the answer to that question is not too difficult, once you know which property holds the value. [...]]]></description>
			<content:encoded><![CDATA[<p>I got an interesting question from one of my co-authors of the <a href="http://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="http://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="http://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="http://lucd.info/wp-content/uploads/2012/01/JSBvariations.jpg"><img class=" wp-image-3906 alignnone" title="variations" src="http://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>
<span id="The_basic_solution"><h2>The basic solution</h2></span>
<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="http://www.lucd.info/category/vsphere/dvswitch/" target="_blank">dvSwitch</a> port information is hiding.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/VMport.png"><img class="alignnone  wp-image-3926" title="VMport" src="http://lucd.info/wp-content/uploads/2012/01/VMport.png" alt="" width="476" height="313" /></a></p>
<p>As a matter of fact the port information is kept with the <a href="http://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="http://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>
<pre class="brush: powershell; title: ; notranslate">
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>
<span id="Annotations"><h4>Annotations</h4></span>
<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="http://lucd.info/wp-content/uploads/2012/01/port-basic.png"><img class="alignnone  wp-image-3918" title="port-basic" src="http://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>
<pre class="brush: powershell; title: ; notranslate">
$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>
<span id="A_faster_solution"><h2>A faster solution</h2></span>
<p>When you visited the <a href="http://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="http://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="http://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>
<pre class="brush: powershell; title: ; notranslate">
$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>
<span id="Annotations_1"><h4>Annotations</h4></span>
<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="http://lucd.info/wp-content/uploads/2012/01/port-fast.png"><img class="alignnone  wp-image-3920" title="port-fast" src="http://lucd.info/wp-content/uploads/2012/01/port-fast.png" alt="" width="531" height="154" /></a></p>
<span id="A_function"><h2>A function</h2></span>
<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>
<pre class="brush: powershell; title: ; notranslate">
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>
<span id="Annotations_2"><h4>Annotations</h4></span>
<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='http://lucd.info/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </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="http://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&#8243;</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>
<pre class="brush: powershell; title: ; notranslate">
Get-dvVmPort | Sort-Object -Property VM,NIC | Select VM,NIC,PortGroup,Port
</pre>
<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="http://lucd.info/wp-content/uploads/2012/01/fport-ex1.png"><img class="alignnone  wp-image-3928" title="fport-ex1" src="http://lucd.info/wp-content/uploads/2012/01/fport-ex1.png" alt="" width="558" height="159" /></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>
<pre class="brush: powershell; title: ; notranslate">
Get-VM -Name &quot;VM[13]&quot; | Get-dvVmPort | Sort-Object -Property VM,NIC | Select VM,NIC,PortGroup,Port
</pre>
<p>This will give</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/fport-ex2.png"><img class="alignnone  wp-image-3930" title="fport-ex2" src="http://lucd.info/wp-content/uploads/2012/01/fport-ex2.png" alt="" width="576" height="88" /></a></p>
<p>And finally an example with the <strong>PortGroup</strong> parameterset.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-dvVmPort -Portgroup (Get-VirtualPortGroup -Distributed) |  Select VM,NIC,PortGroup,Port
</pre>
<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="http://lucd.info/wp-content/uploads/2012/01/fport-ex3.png"><img class="alignnone  wp-image-3931" title="fport-ex3" src="http://lucd.info/wp-content/uploads/2012/01/fport-ex3.png" alt="" width="597" height="126" /></a></p>
<span id="A_new_property"><h2>A new property</h2></span>
<p>If we want to display this port information with each NIC connected to a VM, when we do a <a href="http://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="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/New-VIProperty.html" target="_blank">New-VIProperty</a>.</p>
<p>The <a href="http://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>
<pre class="brush: powershell; title: ; notranslate">
New-VIProperty -Name dvPort -ObjectType NetworkAdapter `
  -Value {
    param($nic)

    $nic.ExtensionData.Backing.Port.PortKey
  } -Force | Out-Null
</pre>
<p>When we do</p>
<pre class="brush: powershell; title: ; notranslate">
Get-VM -Name VM4 | Get-NetworkAdapter | Select Name,NetworkName,dvPort | Format-Table
</pre>
<p>We will get the following.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/newviproperty.png"><img class="alignnone  wp-image-3933" title="newviproperty" src="http://lucd.info/wp-content/uploads/2012/01/newviproperty.png" alt="" width="536" height="98" /></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>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/rV72EKYnFhM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2012/01/29/variations-on-a-port/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2012/01/29/variations-on-a-port/</feedburner:origLink></item>
		<item>
		<title>Get complete vCenter session info</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/RIysJySLnH8/</link>
		<comments>http://www.lucd.info/2012/01/17/get-complete-vcenter-session-info/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 19:03:39 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[event]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Session Manager]]></category>
		<category><![CDATA[SessionManager]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3869</guid>
		<description><![CDATA[There was an interesting thread in the PowerCLI Community today. It raised the question how one could report on the current vCenter sessions, including the IP address or hostname from where the session was started. Unfortunately the SessionManager doesn&#8217;t hold any information from where the session was started. But there are other ways of finding [...]]]></description>
			<content:encoded><![CDATA[<p>There was an interesting <a href="http://communities.vmware.com/thread/343345?tstart=0" target="_blank">thread</a> in the <a href="http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=discussions&amp;start=0" target="_blank">PowerCLI Community</a> today. It raised the question how one could report on the current vCenter sessions, including the <strong>IP address</strong> or <strong>hostname</strong> from where the session was started.</p>
<p>Unfortunately the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.SessionManager.html" target="_blank">SessionManager</a> doesn&#8217;t hold any information from where the session was started.</p>
<p>But there are other ways of finding that information. The <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.event.UserLoginSessionEvent.html" target="_blank">UserLoginSessionEvent</a> object has a property, called <strong>ipAddress</strong>, that has the information we&#8217;re after.</p>
<p>Btw if you are only interested in looking for idle sessions, independent from which host they were started, there is a great post, called <a href="http://blogs.vmware.com/vipowershell/2011/09/list-and-disconnect-vcenter-sessions.html" target="_blank">List and Disconnect vCenter Sessions</a> on the <a href="http://blogs.vmware.com/vipowershell/" target="_blank">PowerCLI blog</a>.<br />
<span id="more-3869"></span></p>
<span id="The_script"><h2>The script</h2></span>
<pre class="brush: powershell; title: ; notranslate">
function Get-VISessionInfo{
&lt;#
.SYNOPSIS  Retrieve vCenter session information
.DESCRIPTION The function will retrieve the open vCenter
  session, including the IP address and hostname from where
  the session was started
.NOTES  Author:  Luc Dekens
.PARAMETER AllowedDifference
  The timestamps from the Session Manager entries and the
  event objects can sometimes differ, depending on the vCenter
  activity. The default is 1 second, but this can be changed
  with this parameter. The unit for this parameter is seconds.
.EXAMPLE
  PS&gt; Get-VISessionInfo
#&gt;

  param(
  [CmdletBinding()]
  [int]$AllowedDifference = 1
  )

  process{
    $sessMgr = Get-View SessionManager
    $oldest = ($sessMgr.SessionList | Sort-Object -Property LoginTime | Select -First 1).LoginTime
    $users = $sessMgr.SessionList | %{$_.UserName}
    $events = Get-VIEvent -MaxSamples ([int]::MaxValue) -Start $oldest.AddHours(-1) |
    where {$_ -is [VMware.Vim.UserLoginSessionEvent] -and $users -contains $_.UserName} |
    Sort-Object -Property CreatedTime

    $allowedDiffTS = New-TimeSpan -Seconds $AllowedDifference

    foreach($session in $sessMgr.SessionList){
      $events |
      where {[math]::Abs(($session.LoginTime.ToLocalTime() - $_.CreatedTime).Ticks) -lt $allowedDiffTS.Ticks -and
        $users -contains $_.UserName} | %{
        New-Object PSObject -Property @{
          &quot;Session login&quot; = $session.LoginTime
          UserName = $_.UserName
          IPAddress = $_.IPAddress
          Hostname = [System.Net.Dns]::GetHostEntry($_.IPAddress).HostName
        }
      }
    }
  }
}
</pre>
<span id="Annotations"><h4>Annotations</h4></span>
<p><strong>Line 24</strong>: The script will look for the session with the oldest login time. This will allow us to limit the number of events that need to be retrieved.</p>
<p><strong>Line 25</strong>: Besides the timestamps, the script will also check if the username that appears in an user session login event, is one of the users that has an open vCenter session.</p>
<p><strong>Line 26-28</strong>: We retrieve the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.event.UserLoginSessionEvent.html" target="_blank">UserLoginSessionEvent</a> for users that have an open vCenter session.</p>
<p><strong>Line 30</strong>: The time difference we allow between the timestamp in the session and the corresponding <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.event.UserLoginSessionEvent.html" target="_blank">UserLoginSessionEvent</a> is converted to a TimeSpan object.</p>
<p><strong>Line 34</strong>: To link a vCenter session to a <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.event.UserLoginSessionEvent.html" target="_blank">UserLoginSessionEvent</a> the script calculates the time difference between the timestamps in the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.event.UserLoginSessionEvent.html" target="_blank">UserLoginSessionEvent</a> and the session object from the SessionManager. If the absolute time difference falls below the accepted time difference ($AllowedDifference), the event is linked to the session.</p>
<p><strong>Line 36-41</strong>: The result is placed in the pipeline</p>
<p><strong>Line 40</strong>: The script converts the IP address to the <strong>hostname</strong> with the <a href="http://msdn.microsoft.com/en-US/library/ms143998(v=vs.80).aspx" target="_blank">GetHostEntry</a> method.</p>
<span id="Sample_usage"><h2>Sample usage</h2></span>
<p>The function is rather simple in use.</p>
<pre class="brush: powershell; title: ; notranslate">

Get-VISessionInfo
</pre>
<p>And the result looks something like this.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/visession.png"><img class="alignnone size-full wp-image-3885" title="visession" src="http://lucd.info/wp-content/uploads/2012/01/visession.png" alt="" width="548" height="166" /></a></p>
<p>Enjoy!</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/RIysJySLnH8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2012/01/17/get-complete-vcenter-session-info/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2012/01/17/get-complete-vcenter-session-info/</feedburner:origLink></item>
		<item>
		<title>Proxy cmdlet revisited: Connect-VIServer and Disconnect-VIServer</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/V3E-HsbfbZM/</link>
		<comments>http://www.lucd.info/2012/01/16/proxy-cmdlet-revisted-connect-viserver-and-disconnect-viserver/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 18:12:05 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[Connect-VIServer]]></category>
		<category><![CDATA[Disconnect-VIServer]]></category>
		<category><![CDATA[PowerCLI]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3855</guid>
		<description><![CDATA[In PowerCLI 5.0.1 a handy feature that showed the connected vSphere Servers in the title bar of the PowerCLI window was apparently removed. In a PowerCLI Community thread some users found this a useful feature that they would like to have back. I&#8217;m sure the PowerCLI Team will listen to their users and fix this [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=overview" target="_blank">PowerCLI 5.0.1</a> a handy feature that showed the connected vSphere Servers in the title bar of the PowerCLI window was apparently removed.<br />
In a PowerCLI Community <a href="http://communities.vmware.com/thread/342796?tstart=0" target="_blank">thread</a> some users found this a useful feature that they would like to have back.<br />
I&#8217;m sure the PowerCLI Team will listen to their users and fix this problem in the coming PowerCLI version.</p>
<p>But while we are waiting for a new PowerCLI build that brings back the title bar text, you can fix this for yourself thanks to the proxy cmdlet feature.</p>
<p><span id="more-3855"></span></p>
<p>Proxy cmdlets is (another) handy feature in PowerShell which allows you to modify and extend existing cmdlets. You can add parameters, change the output and do other crazy things. In the <a href="http://blogs.msdn.com/b/powershell/archive/2009/01/04/extending-and-or-modifing-commands-with-proxies.aspx" target="_blank">Extending and/or Modifing Commands with Proxies</a> post from Jeffrey Snover you can find all the details.</p>
<p>In that same post you can also find the MetaProgramming module which makes it a breeze to customise cmdlets.</p>
<p>You just call the New-ProxyCommand and redirect the output to a .ps1 file, which you can then use to write your customisations for the cmdlet.</p>
<p>In this case I did that for the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Connect-VIServer.html" target="_blank">Connect-VIServer</a> and <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Disconnect-VIServer.html" target="_blank">Disconnect-VIServer</a> cmdlets as follows</p>
<pre class="brush: powershell; title: ; notranslate">

New-ProxyCommand Connect-VIServer &gt; .\Connect-VIServer.ps1

New-ProxyCommand Disconnect-VIServer &gt; .\Disconnect-VIServer.ps1
</pre>
<p>The resulting .ps1 files can now be edited to introduce our customisations to these cmdlets.</p>
<span id="My_Connect-VIServer"><h2>My Connect-VIServer</h2></span>
<pre class="brush: powershell; title: ; notranslate">
function Connect-VIServer{
  [CmdletBinding(DefaultParameterSetName='Default')]
  param(
  [Parameter(ParameterSetName='Default', Mandatory=$true, Position=0)]
  [ValidateNotNullOrEmpty()]
  [System.String[]]
  ${Server},

  [Parameter(ParameterSetName='Default')]
  [ValidateNotNull()]
  [ValidateRange(0, 65535)]
  [System.Int32]
  ${Port},

  [Parameter(ParameterSetName='Default')]
  [ValidateSet('http','https')]
  [System.String]
  ${Protocol},

  [Parameter(ParameterSetName='Default', ValueFromPipeline=$true)]
  [ValidateNotNullOrEmpty()]
  [System.Management.Automation.PSCredential]
  ${Credential},

  [Parameter(ParameterSetName='Default', ValueFromPipeline=$true)]
  [Alias('Username')]
  [System.String]
  ${User},

  [Parameter(ParameterSetName='Default')]
  [System.String]
  ${Password},

  [Parameter(ParameterSetName='Default')]
  [System.String]
  ${Session},

  [Parameter(ParameterSetName='Default')]
  [switch]
  ${NotDefault},

  [Parameter(ParameterSetName='Default')]
  [switch]
  ${SaveCredentials},

  [Parameter(ParameterSetName='Default')]
  [switch]
  ${AllLinked},

  [Parameter(ParameterSetName='Menu', Mandatory=$true)]
  [switch]
  ${Menu})

  begin
  {
    try {
      $outBuffer = $null
      if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
      {
        $PSBoundParameters['OutBuffer'] = 1
      }
      $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Connect-VIServer', [System.Management.Automation.CommandTypes]::Cmdlet)
      $scriptCmd = {&amp; $wrappedCmd @PSBoundParameters }
      $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
      $steppablePipeline.Begin($PSCmdlet)
    } catch {
      Throw
    }
  }

  process
  {
    try {
      $steppablePipeline.Process($_)
    } catch {
      Throw
    }
    switch($defaultVIServers.Count){
      0 {
        $text = &quot;Not Connected&quot;
      }
      1 {
        $text = &quot;Connected to &quot; + $defaultVIServers[0].Name + &quot; as &quot; + $defaultVIServers[0].User
      }
      Default {
        $text = &quot;Connected to &quot; + $defaultVIServers.Count + &quot; servers: &quot;
        $text += [string]::Join(',',($defaultVIServers | %{$_.Name}))
      }
    }
    (Get-Host).UI.RawUI.WindowTitle = $text
  }

  end
  {
    try {
      $steppablePipeline.End()
    } catch {
      Throw
    }
  }
&lt;#

.ForwardHelpTargetName Connect-VIServer
.ForwardHelpCategory Cmdlet

#&gt;
}
</pre>
<span id="Annotations"><h4>Annotations</h4></span>
<p><strong>Line 1,107</strong>: We make this a function<br />
<strong>Line 78,90</strong>: The code we add to the original cmdlet. This will place the text in the title bar.</p>
<span id="My_Disconnect-VIServer"><h2>My Disconnect-VIServer</h2></span>
<pre class="brush: powershell; title: ; notranslate">
function Disconnect-VIServer{
  [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')]
  param(
  [Parameter(Position=0, ValueFromPipeline=$true)]
  [ValidateNotNullOrEmpty()]
  [VMware.VimAutomation.ViCore.Types.V1.VIServer[]]
  ${Server},

  [switch]
  ${Force})

  begin
  {
    try {
      $outBuffer = $null
      if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
      {
        $PSBoundParameters['OutBuffer'] = 1
      }
      $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Disconnect-VIServer', [System.Management.Automation.CommandTypes]::Cmdlet)
      $scriptCmd = {&amp; $wrappedCmd @PSBoundParameters }
      $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
      $steppablePipeline.Begin($PSCmdlet)
    } catch {
      Throw
    }
  }

  process
  {
    try {
      $steppablePipeline.Process($_)
    } catch {
      Throw
    }
    switch($defaultVIServers.Count){
      0 {
        $text = &quot;Not Connected&quot;
      }
      1 {
        $text = &quot;Connected to &quot; + $defaultVIServers[0].Name + &quot; as &quot; + $defaultVIServers[0].User
      }
      Default {
        $text = &quot;Connected to &quot; + $defaultVIServers.Count + &quot; servers: &quot;
        $text += [string]::Join(',',($defaultVIServers | %{$_.Name}))
      }
    }
    (Get-Host).UI.RawUI.WindowTitle = $text
  }

  end
  {
    try {
      $steppablePipeline.End()
    } catch {
      Throw
    }
  }
&lt;#

.ForwardHelpTargetName Disconnect-VIServer
.ForwardHelpCategory Cmdlet

#&gt;
}
</pre>
<span id="Annotations_1"><h4>Annotations</h4></span>
<p><strong>Line 1,65</strong>: We make this a function<br />
<strong>Line 36,48</strong>: The code we add to the original cmdlet. This will place the text in the title bar.</p>
<span id="Usage_samples"><h2>Usage samples</h2></span>
<p>First you will need to dot-source the .ps1 files with the customised versions of both cmdlets.</p>
<pre class="brush: powershell; title: ; notranslate">

. ./Connect-VIServer.ps1

. ./Disconnect-VIServer.ps1
</pre>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/dot-source.png"><img class="alignnone  wp-image-3857" title="dot-source" src="http://lucd.info/wp-content/uploads/2012/01/dot-source.png" alt="" width="330" height="94" /></a></pre>
<p>We now have a function and a cmdlet for both.</p>
<pre class="brush: powershell; title: ; notranslate">

Get-Command Connect-VIServer

Get-Command Disconnect-VIServer
</pre>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/commands.png"><img class="alignnone  wp-image-3858" title="commands" src="http://lucd.info/wp-content/uploads/2012/01/commands.png" alt="" width="521" height="202" /></a></p>
<p>But PowerShell will use a function before a cmdlet when both have the same name. Exactly what we need !</p>
<p>If you want to learn more about these precedences, do a</p>
<pre class="brush: powershell; title: ; notranslate">

Get-Help About_command_precendence
</pre>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/precedence.png"><img class="alignnone  wp-image-3859" title="precedence" src="http://lucd.info/wp-content/uploads/2012/01/precedence.png" alt="" width="517" height="151" /></a></p>
<p>Now we are ready to use our customised cmdlets. When we do a first connect</p>
<pre class="brush: powershell; title: ; notranslate">

$vc = Connect-VIServer -Server MyVC
</pre>
<p>the PowerCLI window will show</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/MyVC-connected1.png"><img class="alignnone  wp-image-3861" title="MyVC-connected" src="http://lucd.info/wp-content/uploads/2012/01/MyVC-connected1.png" alt="" width="406" height="64" /></a></p>
<p>When we connect an additional vSphere Server</p>
<pre class="brush: powershell; title: ; notranslate">

$esx = Connect-VIServer -Server MyEsx1 -User root -Password MyPswd
</pre>
<p>the PowerCLI window will show.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/MyEsx1-connected.png"><img class="alignnone  wp-image-3862" title="MyEsx1-connected" src="http://lucd.info/wp-content/uploads/2012/01/MyEsx1-connected.png" alt="" width="498" height="59" /></a></p>
<p>When we disconnect from one of the vSphere Servers, the title bar will be updated as well.</p>
<pre class="brush: powershell; title: ; notranslate">

Disconnect-VIServer -Server $vc
</pre>
<p>The title bar will show</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/MyVC-disconnected.png"><img class="alignnone  wp-image-3863" title="MyVC-disconnected" src="http://lucd.info/wp-content/uploads/2012/01/MyVC-disconnected.png" alt="" width="496" height="60" /></a></p>
<p>There are of a couple of open problems</p>
<ul>
<li>The initial PowerCLI window shows "<strong>Not connected</strong>". This could eventually be solved by adapting the PowerCLI initialisation script, but I didn't want to change that script</li>
<li>The Disconnect-VIServer cmdlet also accepts a [<strong>string</strong>] for the <strong>Server</strong> argument. The proxy cmdlet doesn't accept that, you will have to give it a VIServer object on the Server parameter.</li>
</ul>
<p>Enjoy !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/V3E-HsbfbZM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2012/01/16/proxy-cmdlet-revisted-connect-viserver-and-disconnect-viserver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2012/01/16/proxy-cmdlet-revisted-connect-viserver-and-disconnect-viserver/</feedburner:origLink></item>
		<item>
		<title>Change the root password in hosts and Host Profiles</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/-21bR_OSyRU/</link>
		<comments>http://www.lucd.info/2012/01/15/change-theroot-password-in-hosts-and-host-profiles/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 21:40:03 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[Host Profile]]></category>
		<category><![CDATA[password]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[root]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3846</guid>
		<description><![CDATA[For good security measures you should change the password of your root account on your ESX(i) servers on a regular basis. Instead of logging on to each and everyone of your ESX(I) servers, you can easily automate this process. But what about the new ESX(i) hosts you will roll out in between root password changes [...]]]></description>
			<content:encoded><![CDATA[<p>For good security measures you should change the password of your root account on your ESX(i) servers on a regular basis. Instead of logging on to each and everyone of your ESX(I) servers, you can easily automate this process.</p>
<p>But what about the new ESX(i) hosts you will roll out in between root password changes and where you use a <strong>Host Profile</strong> to configure these new ESX(i) hosts ? Will you need to run a script after the deployment to change the root password ?</p>
<p>Turns out that you can easily update  the root password in your Host Profile with the help of an SDK method.</p>
<p><span id="more-3846"></span></p>
<span id="The_installed_hosts"><h2>The installed hosts</h2></span>
<p>There are numerous scripts available in the blogosphere to accomplish this. But for good measure, this is one script that can do the task.</p>
<pre class="brush: powershell; title: ; notranslate">
$currentPswd = &quot;currentPassword&quot;
$newPswd = &quot;newPassword&quot;

$excludeServers = &quot;esx51&quot;,&quot;esx56&quot;

$multiState = (Get-PowerCLIConfiguration).DefaultVIServerMode
$warnings = (Get-PowerCLIConfiguration).DisplayDeprecationWarnings
Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Confirm:$false -DisplayDeprecationWarnings:$false | Out-Null

Get-VMHost | where{$excludeServers -notcontains $_.Name.Split('.')[0]} | %{
  Connect-VIServer -Server $_.Name -User root -Password $currentPswd | Out-Null
  Write-Verbose &quot;Connected to $_&quot;
  Set-VMHostAccount -UserAccount root -Password $newPswd -Confirm:$false | Out-Null
  Disconnect-VIServer -Server $_.Name -Confirm:$false
}

Set-PowerCLIConfiguration -DefaultVIServerMode $multiState -DisplayDeprecationWarnings $warnings -Confirm:$false | Out-Null
</pre>
<span id="Annotations"><h4>Annotations</h4></span>
<p><strong>Line 1-2</strong>:  Provide the current and the new password for the root account.</p>
<p><strong>Line 4</strong>: The script allows for ESX(i) hosts whose root password should not be changed to the password specified in this run of the script. These ESX(i) hosts can excluded by adding their hostname to this array.</p>
<p><strong>Line 6-8</strong>: The script needs to run in <strong>Multiple</strong> mode, in other words it needs connections to multiple vSphere servers at the same time. For the run of this script I also disable the warning messages for deprecated properties, this to avoid a long list of warning messages. The script remembers the current settings before changing them.</p>
<p><strong>Line 10</strong>: The script gets all the ESX(i) servers and excludes the ones we defined in the array in line 4.</p>
<p><strong>Line 11-14</strong>: The script makes a connection to the ESX(i) server and changes the password of the root account.</p>
<p><strong>Line 12</strong>: If you want to track the ESX(i) hosts for which the script is changing the root password, you can set the $verbosePreference variable to <strong>Continue</strong> instead of the default <strong>SilentlyContinue</strong>.</p>
<p><strong>Line 17</strong>: The script restores the PowerCLI Configuration settings.</p>
<span id="The_Host_Profile"><h2>The Host Profile</h2></span>
<p>When you use Host Profiles to configure your newly deployed ESX(i) servers, you will need to update the root account in those Host Profiles on a regular basis as well. That way the new ESX(i) hosts you roll out will immediately have the current root password.</p>
<pre class="brush: powershell; title: ; notranslate">
function Set-VMHostProfileExtended{
&lt;#
.SYNOPSIS  Update the root password in a Host Profile
.DESCRIPTION The function will update the root password in
  a Host Profile.
.NOTES  Author:  Luc Dekens
.PARAMETER Profile
  The Host Profile for which you want to change the root
  password. You can pass the name of the Host Profile
  or the VMHostProfile object
.PARAMETER AdminPassword
  The new root password.
.EXAMPLE
  PS&gt; $prof = Get-VMHostProfile -Name MyProfile
  PS&gt; Set-VMHostProfileExtended -Profile $prof -AdminPassword &quot;abc&quot;
#&gt;

  param(
  [CmdletBinding()]
  [parameter(Mandatory = $true, ValueFromPipeline = $true)]
  [PSObject]$Profile,
  [string]$AdminPassword
  )

  begin{
    function Copy-Property ($From, $To, $PropertyName =&quot;*&quot;)
    {
      foreach ($p in Get-Member -In $From -MemberType Property -Name $propertyName)
      {        trap {
          Add-Member -In $To -MemberType NoteProperty -Name $p.Name -Value $From.$($p.Name) -Force
          continue
        }
        $To.$($P.Name) = $From.$($P.Name)
      }
    }
  }

  process{
    if($Profile.GetType().Name -eq &quot;string&quot;){
      $Profile = Get-VMHostProfile -Name $Profile -Server $defaultVIServers[0]
    }

    $spec = New-Object VMware.Vim.HostProfileCompleteConfigSpec

    Copy-Property -From $Profile.ExtensionData.Config -To $spec

    $secpol = New-Object VMware.Vim.ProfilePolicy
    $secpol.Id = &quot;AdminPasswordPolicy&quot;
    $secpol.PolicyOption = New-Object VMware.Vim.PolicyOption
    $secpol.PolicyOption.Id = &quot;FixedAdminPasswordOption&quot;
    $secpol.PolicyOption.Parameter += New-Object VMware.Vim.KeyAnyValue
    $secpol.PolicyOption.Parameter[0].Key = &quot;password&quot;
    $secpol.PolicyOption.Parameter[0].Value = New-Object VMware.Vim.PasswordField
    $secpol.PolicyOption.Parameter[0].Value.Value = $AdminPassword
    $spec.ApplyProfile.Security.Policy = @($secpol)

    $hp.ExtensionData.UpdateHostProfile($spec)

    Get-VMHostProfile -Name $Profile.Name
  }
}
</pre>
<span id="Annotations_1"><h4>Annotations</h4></span>
<p><strong>Line 26-35</strong>: The function needs to copy all the <strong>Config</strong> properties from the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.profile.host.HostProfile.html" target="_blank">HostProfile</a> to the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.profile.host.HostProfile.CompleteConfigSpec.html" target="_blank">HostProfileCompleteConfigSpec</a> object. Instead of reinventing the wheel, I used a function called <a href="http://blogs.msdn.com/b/powershell/archive/2006/12/29/use-copy-property-to-make-it-easier-to-write-read-and-review-scripts.aspx">Copy-Property function</a> from <strong>Dennis Verwiej</strong>.</p>
<p><strong>Line 39-41</strong>: My simplistic Object By Name (OBN) implementation.</p>
<p><strong>Line 45</strong>: The copy of the <strong>Config</strong> property to the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.profile.host.HostProfile.CompleteConfigSpec.html" target="_blank">HostProfileCompleteConfigSpec</a> object.</p>
<p><strong>Line 47-55</strong>: To the copied HostProfile configuration the script adds the <strong>AdminPasswordPolicy</strong> definitions.</p>
<p><strong>Line 57</strong>: The <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.profile.host.HostProfile.html" target="_blank">HostProfile</a> is updated with the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.profile.host.HostProfile.html#update" target="_blank">UpdateHostProfile</a> method.</p>
<p><strong>Line 59</strong>: To emulate the behaviour of the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Set-VMHostProfile.html" target="_blank">Set-VMHostProfile</a> cmdlet, the function places the updated <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/VMHostProfile.html" target="_blank">VMHostProfile</a> object on the pipeline.</p>
<span id="Sample_usage"><h2>Sample usage</h2></span>
<p>The function to update the Host Profile can be called with the Host Profile as a parameter.</p>
<pre class="brush: powershell; title: ; notranslate">
$hostProf = &quot;MyProfile&quot;
$newProf = Set-VMHostProfileExtended -Profile $hostProf -AdminPassword &quot;secret&quot;
</pre>
<p>or</p>
<pre class="brush: powershell; title: ; notranslate">
$hostProf = Get-VMHostProfile -Name MyProfile
$newProf = Set-VMHostProfileExtended -Profile $hostProf -AdminPassword &quot;secret&quot;
</pre>
<p>Or you can place the Host Profile on the pipeline.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-VMHostProfile -Name MyProfile | Set-VMHostProfileExtended -AdminPassword &quot;secret&quot;
</pre>
<p>Notice that I called the function Set-VMHostProfileExtended. The reason for that is that one can update several other settings in a Host Profile this way. I&#8217;ll probably add some other settings to the function in a later stage.</p>
<p>Enjoy !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/-21bR_OSyRU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2012/01/15/change-theroot-password-in-hosts-and-host-profiles/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2012/01/15/change-theroot-password-in-hosts-and-host-profiles/</feedburner:origLink></item>
		<item>
		<title>PowerCLI 5.0.1 goes Cloud</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/MphI8FwmN-s/</link>
		<comments>http://www.lucd.info/2012/01/10/powercli-5-0-1-goes-cloud/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 04:55:32 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vCD]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[PowerCLI]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3811</guid>
		<description><![CDATA[As a belated Christmas present the new PowerCLI version 5.0.1 is available. This new build brings us the Cloud snapin. The availability of vCD cmdlets was already announced during VMworld 2011 and now the vCD cmdlets make their public appearance. The first release of the Cloud snapin brings us primarily Get type cmdlets. But there [...]]]></description>
			<content:encoded><![CDATA[<p>As a belated Christmas present the new <a href="http://www.vmware.com/downloads/download.do?downloadGroup=PCLI501" target="_blank"><strong>PowerCLI version 5.0.1</strong></a> is available. This new build brings us the <strong>Cloud snapin</strong>. The availability of vCD cmdlets was already announced during <strong>VMworld 2011</strong> and now the <strong>vCD cmdlets</strong> make their public appearance.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/powercli-cloud1.png"><img class="alignnone size-full wp-image-3815" title="powercli-cloud" src="http://lucd.info/wp-content/uploads/2012/01/powercli-cloud1.png" alt="" width="545" height="407" /></a></p>
<p>The first release of the Cloud snapin brings us primarily <strong>Get</strong> type cmdlets. But there is more, just as the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-View.html" target="_blank">Get-View</a> cmdlet opened up access to the <strong>vSphere API</strong>, the new <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-CIView.html" target="_blank">Get-CIView</a> cmdlet, and the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/ExtensionData.html" target="_blank">ExtensionData</a> property, opens up access  to all the <strong>vCD APIs</strong>.</p>
<p><span id="more-3811"></span></p>
<p>First a quick list of all the cmdlets that are available in the Cloud snapin.</p>
<p><iframe src="https://sheet.zoho.com/publish/dekens.luc/powercli501-xref" frameborder="0" scrolling="no" width="500" height="400"></iframe></p>
<p><span style="font-size: x-small;">PS: the list above has been created with the script from my <a href="http://www.lucd.info/2011/03/04/powercli-cmdlet-xref-another-look/" target="_blank">PowerCLI cmdlet XRef – Another look</a> post.</span></p>
<p>The PowerCLI help pages are available <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/index.html" target="_blank">online</a>.</p>
<p>Btw the <strong>CI</strong> noun prefix that you will see as a prefix to most of the Cloud cmdlets nouns, stands for <strong>Cloud Infrastructure</strong>.</p>
<p>To start a session you use the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Connect-CIServer.html" target="_blank">Connect-CIServer</a> cmdlet, similar to what you do with the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Connect-VIServer.html" target="_blank">Connect-VIServer</a> cmdlet. The difference is that you will have to specify a <strong>vCloud Director server</strong> instead of a vSphere Server.</p>
<pre class="brush: powershell; title: ; notranslate">
Connect-Ciserver -Server MyVCD -User Luc -Password MyPswd
</pre>
<p>And you&#8217;ll immediately notice a first change, the Certificate warning message has changed. You are prompted to answer with one of the listed options.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/connect-ciserver.png"><img class="alignnone  wp-image-3826" title="connect-ciserver" src="http://lucd.info/wp-content/uploads/2012/01/connect-ciserver.png" alt="" width="514" height="347" /></a></p>
<p>Does this mean you will have to do this every time (provided you don&#8217;t update the Certificate) ?<br />
No, the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Set-PowerCLIConfiguration.html" target="_blank">Set-PowerCLIConfiguration</a> cmdlet has been extended with a new parameter, called InvalidCertificateAction. You can provide the parameter with one of the values of the BadCertificateAction enumeration, and PowerCLI will take that as the default action for future connects.</p>
<p>Notice that we didn&#8217;t specify an Organization name, through the <strong>Org</strong> parameter, to the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Connect-CIServer.html" target="_blank">Connect-CIServer</a> cmdlet. That means your session will get connected to the System organization.</p>
<p>Once you are connected, you can start having a look around with the help of all the Get type cmdlets. The VMs in the Cloud</p>
<pre class="brush: powershell; title: ; notranslate">
Get-CIVM
</pre>
<p>returns something like<br />
<a href="http://lucd.info/wp-content/uploads/2012/01/get-civm.png"><img class="alignnone  wp-image-3827" title="get-civm" src="http://lucd.info/wp-content/uploads/2012/01/get-civm.png" alt="" width="510" height="67" /></a></p>
<p>The Roles that are present</p>
<pre class="brush: powershell; title: ; notranslate">

Get-CIRole
</pre>
<p>which gives</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/get-cirole.png"><img class="alignnone  wp-image-3828" title="get-cirole" src="http://lucd.info/wp-content/uploads/2012/01/get-cirole.png" alt="" width="508" height="96" /></a></p>
<p>And the available vApps in this cloud</p>
<pre class="brush: powershell; title: ; notranslate">

Get-CIvApp
</pre>
<p>This tells us there currently 4 vApps present</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/get-civapp.png"><img class="alignnone  wp-image-3829" title="get-civapp" src="http://lucd.info/wp-content/uploads/2012/01/get-civapp.png" alt="" width="478" height="89" /></a></p>
<p>But is this all we can do ? Only produce reports of what is available in our cloud ?</p>
<p>No, luckily there are already a couple of other cmdlets that will allow you to populate your cloud.</p>
<p>Let&#8217;s take the case where we want to import a VM from our vCenter into our Cloud.</p>
<p>First connect to the vCenter server, then get the VM you want to import and pass the VM to the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Import-CIVApp.html" target="_blank">Import-CIVApp</a> cmdlet. Note that for the creation of this new vApp you will have to provide an <strong>Organization VDC</strong>. The organization VDCs can be listed with the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-OrgVdc.html" target="_blank">Get-OrgVdc</a> cmdlet.</p>
<pre class="brush: powershell; title: ; notranslate">

Connect-VIServer -Server MyVC

$orgVdc = Get-OrgVdc -Name MyOrgVdc

Get-VM -Name TestVM2 | Import-CIVApp -OrgVdc $orgVdc -Name TestVapp
</pre>
<p>You will first see that VM, called TestVM2, is <strong>cloned</strong> in your vCenter, followed by an import of the clone into your Cloud. This import will display a progress bar.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/import-civapp.png"><img class="alignnone  wp-image-3830" title="import-civapp" src="http://lucd.info/wp-content/uploads/2012/01/import-civapp.png" alt="" width="506" height="47" /></a></p>
<p>The VM will be part of the new Cloud vApp called <strong>TestVapp</strong>.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/get-civapp2.png"><img class="alignnone  wp-image-3831" title="get-civapp2" src="http://lucd.info/wp-content/uploads/2012/01/get-civapp2.png" alt="" width="502" height="101" /></a></p>
<p>And the imported VM is in the new vApp called TestVapp.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/get-civm2.png"><img class="alignnone  wp-image-3832" title="get-civm2" src="http://lucd.info/wp-content/uploads/2012/01/get-civm2.png" alt="" width="508" height="87" /></a></p>
<p>Adding additional VMs to this vApp is done this way.</p>
<pre class="brush: powershell; title: ; notranslate">

Get-VM -Name TestVM3 | Import-CIVApp -Name TestVapp
</pre>
<p>That&#8217;s all there is to it.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/get-civm3.png"><img class="alignnone  wp-image-3833" title="get-civm3" src="http://lucd.info/wp-content/uploads/2012/01/get-civm3.png" alt="" width="506" height="97" /></a></p>
<p>Now what if you want to do something that is not (yet) covered by the Cloud snapin cmdlets ?</p>
<p>With the <strong>Get-CIView</strong> cmdlet and the <strong>ExtensionData</strong> property on the Cloud objects, you can have access to all the vCloud object properties and methods.</p>
<p>If you intend to use these vCloud .Net object, I advise to have the reference guide available. Download the <a href="http://communities.vmware.com/community/vmtn/developer/forums/vcloudsdk-net?view=overview" target="_blank">VMware vCloud SDK for .Net</a> file, extract the files from the ZIP archive and then open <strong>.\VMware-vCloudDirector-.NetSDK-1.5.0.2\Docs\ndoc3_msdn_temp\index.html</strong> from the folder where you unzipped the archive.</p>
<p>A quick sample, where we list the  methods accessible through the <strong>ExtensionData</strong> of a VM.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/vm-methods.png"><img class="alignnone  wp-image-3835" title="vm-methods" src="http://lucd.info/wp-content/uploads/2012/01/vm-methods.png" alt="" width="504" height="395" /></a></p>
<p>The other way to get there is through the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-CIView.html" target="_blank">Get-CIView</a> cmdlet. This gives access to the same methods (and properties).</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/vm-methods2.png"><img class="alignnone  wp-image-3836" title="vm-methods2" src="http://lucd.info/wp-content/uploads/2012/01/vm-methods2.png" alt="" width="510" height="236" /></a></p>
<p>The access to these methods comes in handy when we need to perform some action that is not available through the cmdlets.</p>
<p>As an example, we want to <strong>delete</strong> the VM called TestVM3 from the TestVapp vApp. With the access to the vCD API this is now a piece of cake.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/vm-delete.png"><img class="alignnone  wp-image-3837" title="vm-delete" src="http://lucd.info/wp-content/uploads/2012/01/vm-delete.png" alt="" width="515" height="116" /></a></p>
<p>That was my short tour of the Cloud snapin, but it only scratched the surface. There&#8217;s tons more of good stuff to be discovered.</p>
<p>Before I forget, make sure to <strong>select</strong> the Cloud snapin when you install/upgrade PowerCLI 5.0.1. By default the Cloud snapin is not installed !</p>
<p>Needless to say that there are <a href="http://www.vmware.com/support/developer/PowerCLI/changelog.html#PowerCLI501" target="_blank">other improvements</a> in <strong>PowerCLI 5.0.1</strong>. One that I will definitely have a closer look at is the new <strong>XML</strong> feature that is provided with the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-EsxCli.html" target="_blank">Get-EsxCli</a> cmdlet.</p>
<p>And btw, the mixup of the <strong>FreeSpaceGB</strong> and <strong>CapacityGB</strong> properties, both in the objects returned by the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI501/html/Get-Datastore.html" target="_blank">Get-Datastore</a> cmdlet, is fixed <img src='http://lucd.info/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Enjoy PowerCLI 5.0.1 !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/MphI8FwmN-s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2012/01/10/powercli-5-0-1-goes-cloud/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2012/01/10/powercli-5-0-1-goes-cloud/</feedburner:origLink></item>
		<item>
		<title>Will Invoke-VMScript work ?</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/Z8P5vslUDXY/</link>
		<comments>http://www.lucd.info/2012/01/01/will-invoke-vmscript-work/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 22:36:50 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Virtual Machine]]></category>
		<category><![CDATA[Invoke-VMScript]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3798</guid>
		<description><![CDATA[The Invoke-VMScript cmdlet can be a very useful cmdlet, but sometimes it will fail against one or more of your VMs. And it is not always immediately clear why the Invoke-VMScript cmdlet will not work against that specific VM. The cmdlet help contains a number of prerequisites, but how do you verify if all the [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI50/html/Invoke-VMScript.html" target="_blank">Invoke-VMScript</a> cmdlet can be a very useful cmdlet, but sometimes it will fail against one or more of your VMs. And it is not always immediately clear why the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI50/html/Invoke-VMScript.html" target="_blank">Invoke-VMScript</a> cmdlet will not work against that specific VM.<br />
The cmdlet help contains a number of <strong>prerequisites</strong>, but how do you verify if all the prerequisites are fulfilled?<br />
I decided to create a function that would verify the prerequisites, and that would, if requested, which of the prerequisites was missing.</p>
<p><span id="more-3798"></span></p>
<span id="The_prerequisites"><h2>The prerequisites</h2></span>
<span id="Official"><h3>Official</h3></span>
<p>The official prerequisites are all documented in the help for the <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI50/html/Invoke-VMScript.html" target="_blank">Invoke-VMScript</a> cmdlet. The following table is a summary.</p>
<table style="width: 515px; height: 222px;" border="0" cellspacing="0" cellpadding="0">
<colgroup>
<col width="324" />
<col width="87" />
<col width="97" />
<col width="90" /> </colgroup>
<tbody>
<tr>
<td width="324" height="20">PowerCLI</td>
<td style="text-align: center;" width="87">4.1</td>
<td style="text-align: center;" width="97">4.1U1</td>
<td style="text-align: center;" width="90">5</td>
</tr>
<tr>
<td height="20">only 32-bit engine</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">VMware Tools installed</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">read access to VM folder</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">Virtual Machine.Interaction.Console privilege</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">VM powered on</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">port 902 to ESX(i) hosting the VM</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">VIX 1.6.2</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;"></td>
</tr>
<tr>
<td height="20">VIX 1.10</td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td width="324" height="40">Windows XP, Windows 7, Windows 2003 Server, Windows 2008 Server,Redhat Enterprise 5</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
</tbody>
</table>
<span id="Unofficial"><h3>Unofficial</h3></span>
<p>From my own experience and from several posts in the <a href="http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=discussions&amp;start=0" target="_blank">PowerCLI Community</a>, I have 2 additional prerequisites.</p>
<ul>
<li>The cmdlet seems to work most of the time when the guest OS is <strong>Windows 2008 R2</strong>. Note that there have been reports about errors with this OS. In the current PowerCLI build Windows 2008 R2 is <strong>not</strong> in the list of supported guest OS.</li>
<li>When you use the hostname in the Connect-VIServer cmdlet, the Invoke-VMScript doesn&#8217;t seem to work. When you do the Connect-VIServer with the <strong>FQDN</strong> or the <strong>IP address</strong>, the cmdlet works. The error message looks like this</li>
</ul>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/invoke-connect.png"><img class="alignnone  wp-image-3801" title="invoke-connect" src="http://lucd.info/wp-content/uploads/2012/01/invoke-connect.png" alt="" width="652" height="67" /></a></p>
<p>The list of my 2 non-official prerequisites</p>
<table style="width: 517px; height: 62px;" border="0" cellspacing="0" cellpadding="0">
<colgroup>
<col width="324" />
<col width="87" />
<col width="97" />
<col width="90" /> </colgroup>
<tbody>
<tr>
<td width="324" height="20">PowerCLI</td>
<td style="text-align: center;" width="87">4.1</td>
<td style="text-align: center;" width="97">4.1U1</td>
<td style="text-align: center;" width="90">5</td>
</tr>
<tr>
<td height="20">Windows 2008 R2 Server</td>
<td></td>
<td></td>
<td style="text-align: center;">x</td>
</tr>
<tr>
<td height="20">Connected with FQDN or IP</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
<td style="text-align: center;">x</td>
</tr>
</tbody>
</table>
<span id="The_Script"><h2>The Script</h2></span>
<pre class="brush: powershell; title: ; notranslate">
function Test-InvokeVMScript{
&lt;#
.SYNOPSIS  Test if Invoke-VMScript will work
.DESCRIPTION The function verifies if all prerequisites
  are present to use the Invoke-VMScript cmdlet.
.NOTES  Author:  Luc Dekens
.PARAMETER VM
  The virtual machine for which you want to test the
  prerequisites. You can pass the name of the virtual
  machine or the VM object
.PARAMETER Official
  This switch specifies if only the official prerequistes
  should be verified or not. The default value is $True,
  so only the official prerequisites
.PARAMETER Detail
  Switch that specifies if all the prerequisite details
  should be returned or not. The default is $False
.EXAMPLE
  PS&gt; Test-InvokeVMScript -VM $vm -Detail
.EXAMPLE
  PS&gt; Get-VM VM* | Test-InvokeVMScript -Official:$false
#&gt;

  param(
  [CmdletBinding()]
  [parameter(Mandatory = $true, ValueFromPipeline = $true)]
  [PSObject]$VM,
  [switch]$Official = $True,
  [switch]$Detail
  )

  begin{
    $pCLIMajor,$pCLIMinor = Get-PowerCLIVersion | %{$_.Major,$_.Minor}
    $apiMajor,$apiMinor = (Get-View ServiceInstance).Content.About.ApiVersion.Split('.')
  }

  process{
    if($VM.GetType().Name -eq &quot;string&quot;){
      $VM = Get-VM -Name $VM
    }

    $condPoweredOn = $condCpu = $condTools = $condPort = $condRead = $condRole = $condOS = $False

    # Common prerequisites

    # Powered on
    if($vm.PowerState -eq &quot;PoweredOn&quot;){
      $condPoweredOn = $True
    }

    # 32-bit engine
    if ($env:Processor_Architecture -eq &quot;x86&quot;){
      $condCpu = $true
    }

    # Tools installed
    if($VM.Guest.State -eq &quot;Running&quot; -and $VM.ExtensionData.Summary.Guest.ToolsVersionStatus -eq &quot;guestToolsCurrent&quot;){
      $condTools = $True
    }

    # Port 902 open
    $originalEA = $ErrorActionPreference
    $ErrorActionPreference = “SilentlyContinue”
    $socket = New-Object Net.Sockets.TcpClient
    $socket.Connect($VM.Host.Name,902)
    if($socket.Connected){
      $condPort = $True
      $socket.Close()
    }
    Remove-Variable -Name socket -Confirm:$false
    $ErrorActionPreference = $originalEA

    # Folder read access
    $datastore,$file = $VM.ExtensionData.Config.Files.VmPathName.Split(']')
    $datastoreName = $datastore.Trim('[')
    $fileName = $file.Split('/')[1]
    $file = $file.TrimStart(' ')
    $ds = Get-Datastore -Name $datastoreName
    New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root '\' | Out-Null
    $currentProgPref = $ProgressPreference
    $ProgressPreference = 'SilentlyContinue'
    Copy-DatastoreItem -Item ('DS:\' + $file) -Destination $env:Temp -ErrorAction SilentlyContinue
    $ProgressPreference = $currentProgPref
    Remove-PSDrive -Name DS
    $path = $env:Temp + '\' + $fileName
    $condRead = Test-Path -Path $path
    if($condRead){
      Remove-Item -Path $path -Confirm:$false
    }

    # Privilege
    $authMgr = Get-View AuthorizationManager
    $role = $authMgr.RoleList | where {$vm.ExtensionData.EffectiveRole -eq $_.RoleId}
    $condRole = $role.Privilege -contains &quot;VirtualMachine.Interact.ConsoleInteract&quot;

    # Supported OS
    $supportedOS = &quot;winLonghornGuest&quot;,  # Windows 2008
    &quot;winLonghorn64Guest&quot;,               # Windows 2008 (64 bit)
    &quot;windows7Guest&quot;,                     # Windows 7
    &quot;windows7_64Guest&quot;,                 # Windows 7 (64 bit)
    &quot;windows7Server64Guest&quot;,            # Windows Server 2008 R2 (64 bit)
    &quot;winXPProGuest&quot;,                     # Windows XP Professional
    &quot;winXPPro64Guest&quot;,                   # Windows XP Professional Edition (64 bit)
    &quot;winXPHomeGuest&quot;,                   # Windows XP Home Edition
    &quot;rhel5Guest&quot;,                       # Red Hat Enterprise Linux 5
    &quot;rhel5_64Guest&quot;,                     # Red Hat Enterprise Linux 5 (64 bit)
    &quot;rhel6Guest&quot;,                       # Red Hat Enterprise Linux 6
    &quot;rhel6_64Guest&quot;                     # Red Hat Enterprise Linux 6 (64 bit)
    $guestId = $VM.ExtensionData.Summary.Guest.GuestId
    if($guestId -like &quot;winNet*&quot; -or $supportedOS -contains $guestId){
      $condOS = $true
    }

    # Version dependent prerequisites
    $propertiesVix =[System.Diagnostics.FileVersionInfo]::GetVersionInfo($env:programfiles + '\VMware\VMware VIX\VixCOM.dll')
    $majorVix = $propertiesVix.FileMajorPart
    $minorVix = $propertiesVix.FileMinorPart
    $buildVix = $propertiesVix.FileBuildPart
    $versionVix = ([string]$majorVix + '.' + [string]$minorVix + '.' + [string]$buildVix)

    if(($pCLIMajor -eq 5 -and $versionVix -eq '1.10.0') -or
    ($pCLIMajor -eq 4 -and $versionVix -eq '1.6.2')){
      $condVix = $true
    }

    # Unofficial conditions
    if(!$Official){
      $condFQDN_U = $condOS_U = $False

      # OS that seems to work (most of the time)
      if($guestId -like &quot;windows7Server64Guest&quot;){  # Windows Server 2008 R2 (64 bit)
        $condOS_U = $True
      }

      # Short name
      $condFQDN_U = $global:DefaultVIserver.Name.Contains('.')
    }

    # Result
    if($Official){
      $result = $condPoweredOn -and $condCpu -and $condTools -and
        $condPort -and $condRead -and $condRole -and $condOS
    }
    else{
      $result = $condPoweredOn -and $condCpu -and $condTools -and
        $condPort -and $condRead -and $condRole -and
        ($condOS -or $condOS_U) -and $condFQDN_U
    }

    $resultObj = New-Object PSObject -Property @{
      VM = $VM.Name
      OK = $result
    }
    if($Detail){
      $resultObj = $resultObj |
      Add-Member -Name PoweredOn -Value $condPoweredOn -MemberType NoteProperty -PassThru |
      Add-Member -Name X86Engine -Value $condCpu -MemberType NoteProperty -PassThru |
      Add-Member -Name ToolsInstalled -Value $condTools -MemberType NoteProperty -PassThru |
      Add-Member -Name Port902Open -Value $condPort -MemberType NoteProperty -PassThru |
      Add-Member -Name FolderReadAccess -Value $condRead -MemberType NoteProperty -PassThru |
      Add-Member -Name PrivilegeConsoleInteraction -Value $condRole -MemberType NoteProperty -PassThru |
      Add-Member -Name SupportedOS -Value $condOs -MemberType NoteProperty -PassThru
      if(!$Official){
        $resultObj = $resultObj |
        Add-Member -Name FQDNorIPConnection -Value $condFQDN_U -MemberType NoteProperty -PassThru
      }
    }
    $resultObj
  }
}
</pre>
<span id="Annotations"><h4>Annotations</h4></span>
<p><strong>Line 32-35</strong>: Retrieve some properties the script will use later.</p>
<p><strong>Line 38-40</strong>: My poor man&#8217;s Object By Name (OBN) implementation.</p>
<p><strong>Line 42</strong>: Set all prerequisites to $false</p>
<p><strong>Line 73-89</strong>: To test if the caller has read access to the VM folder, the script will copy the VMX file to local storage.</p>
<p><strong>Line 82</strong>: This is the major bottleneck in the function. The <a href="http://www.vmware.com/support/developer/PowerCLI/PowerCLI50/html/Copy-DatastoreItem.html" target="_blank">Copy-DatastoreItem</a> cmdlet is quite slow compared to the other PowerCLI cmdlets.</p>
<p><strong>Line 110</strong>: All Windows Server 2003 variations have a guestId that starts with &#8220;winNet&#8221;. See the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html" target="_blank">VirtualMachineGuestOsIdentifier</a> enumeration.</p>
<p><strong>Line 131-133</strong>: Chekc if the guest OS is Windows 2009 R2. If you don&#8217;t want this test, just comment out these lines.</p>
<p><strong>Line 136</strong>: By testing if there any dots in the name, we can verify if it is a Fully Qualified Domain Name or an IP address.</p>
<span id="Sample_use"><h2>Sample use</h2></span>
<p>A very straightforward example</p>
<pre class="brush: powershell; title: ; notranslate">
$vm = Get-VM -Name MyVM
Test-InvokeVMScript -VM $vm
</pre>
<p>This will return a simple object, where the OK property will say if the prerequisites are met or not.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/invoke-ex1.png"><img class="alignnone  wp-image-3802" title="invoke-ex1" src="http://lucd.info/wp-content/uploads/2012/01/invoke-ex1.png" alt="" width="387" height="53" /></a></p>
<p>If we want to know which of the prerequisites failed, we can do</p>
<pre class="brush: powershell; title: ; notranslate">
$vm = Get-VM -Name MyVM
Test-InvokeVMScript -VM $vm -Detail
</pre>
<p>From the output we can immediately see why the Invoke-VMScript cmdlet would fail.</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/invoke-ex2.png"><img class="alignnone  wp-image-3803" title="invoke-ex2" src="http://lucd.info/wp-content/uploads/2012/01/invoke-ex2.png" alt="" width="313" height="107" /></a></p>
<p>Looks like we are not running this in a 32-bit engine.</p>
<p>To also see my non-official prerequisites, we can do</p>
<pre class="brush: powershell; title: ; notranslate">
Get-VM MyVM2 | Test-InvokeVMScript -Official:$false -Detail
</pre>
<p>This produces the following</p>
<p><a href="http://lucd.info/wp-content/uploads/2012/01/invoke-ex3.png"><img class="alignnone  wp-image-3804" title="invoke-ex3" src="http://lucd.info/wp-content/uploads/2012/01/invoke-ex3.png" alt="" width="313" height="122" /></a></p>
<p>All the official prerequisites are fulfilled, but it looks as if our Connect-VIServer might have been done with a short hostname.</p>
<p>Let me know if you know of any other prerequisites, and I will add them to the function.</p>
<p>Enjoy the function.</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/Z8P5vslUDXY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2012/01/01/will-invoke-vmscript-work/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2012/01/01/will-invoke-vmscript-work/</feedburner:origLink></item>
		<item>
		<title>vSphere 5 Top 10 – VMFS5</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/QgAjXoN87JI/</link>
		<comments>http://www.lucd.info/2011/12/19/vsphere-5-top-10-vmfs5/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 21:22:05 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[2011]]></category>
		<category><![CDATA[Dutch]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[VMFS5]]></category>
		<category><![CDATA[VMUG]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[datastore]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3772</guid>
		<description><![CDATA[Continuing my Dutch VMUG Event 2011 presentation series with a post on the VMFS5 feature. This feature clocked in at position 8 in the Top 10. With VMFS5 comes a bunch of new features. Just to name a few: 64TB VMFS Volumes in 1 extent 64TB physical RDM Unified block size of 1MB Support for [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing my <a href="http://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> series with a post on the <strong>VMFS5</strong> feature. This feature clocked in at position 8 in the Top 10.</p>
<p>With <strong>VMFS5</strong> comes a bunch of new features. Just to name a few:</p>
<ul>
<li>64TB VMFS Volumes in 1 extent</li>
<li>64TB physical RDM</li>
<li>Unified block size of 1MB</li>
<li>Support for more files (&gt; 100000)</li>
</ul>
<p>For a complete list of the features that <strong>VMFS5</strong> introduces, have a look at <a href="http://twitter.com/#!/VMwareStorage" target="_blank">Cormac</a>&#8216;s post, called <a href="http://blogs.vmware.com/vsphere/2011/07/new-vsphere-50-storage-features-part-1-vmfs-5.html" target="_blank">vSphere 5.0 Storage Features Part 1 &#8211; VMFS-5</a>.</p>
<p><span id="more-3772"></span></p>
<p>The vSphere 5 Client has an option to upgrade your <strong>VMFS3</strong> datastores to <strong>VMFS5</strong> datastores.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vmfs3-vclient-vsphere5-upgrade.png"><img class="alignnone  wp-image-3776" title="vmfs3-vclient-vsphere5-upgrade" src="http://lucd.info/wp-content/uploads/2011/12/vmfs3-vclient-vsphere5-upgrade.png" alt="" width="566" height="182" /></a></p>
<p>Handy option, but we want to <strong>automate</strong> this of course <img src='http://lucd.info/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>And as a bonus I&#8217;ll throw in a function to get the <strong>partition information</strong> from a datastore.</p>
<span id="The_script"><h2>The script</h2></span>
<pre class="brush: powershell; title: ; notranslate">
function ConvertTo-Vmfs5{
&lt;#
.SYNOPSIS  Upgrade a datastore to VMFS5
.DESCRIPTION The function will convert the datastores that
  are passed to it to VMFS5.
.NOTES  Author:  Luc Dekens
.PARAMETER Datastore
  The datastore(s) to be upgraded
  The parameter accepts a string or an object returned by the
  Get-Datastore cmdlet.
.EXAMPLE
  PS&gt; ConvertTo-Vmfs5 -Datastore &quot;DS*&quot;
.EXAMPLE
  PS&gt; Get-Datastore -Name &quot;DS1&quot; | ConvertTo-Vmfs5
#&gt;

  param(
  [CmdletBinding()]
  [parameter(Mandatory = $true, ValueFromPipeline = $true)]
  [PSObject[]]$Datastore
  )

  process{
    foreach($ds in $Datastore){
      if($ds.getType().Name -eq &quot;string&quot;){
        $ds = Get-Datastore -Name $ds
      }
      $poweredHosts = $ds.ExtensionData.Host | %{Get-View -Id $_.Key} |
      where {$_.Runtime.PowerState -eq &quot;PoweredOn&quot;}

      $oldHost = $poweredHosts |
      where {$_.Capability.SupportedVmfsMajorVersion -notcontains 5}
      if($oldHost){
        Write-Warning &quot;One of the connected hosts doesn't support VMFS5&quot;
        exit
      }
      $vmfsPath = $ds.ExtensionData.Host[0].MountInfo.Path
      $storSys = Get-View ($poweredHosts | Get-Random).ConfigManager.StorageSystem

      $storSys.UpgradeVmfs($vmfsPath)
    }
  }
}

function Get-VmfsPartitionInfo{
&lt;#
.SYNOPSIS  Retrieves partition info for a datastore
.DESCRIPTION The function will retrieve partition information
  for one or more datastores
.NOTES  Author:  Luc Dekens
.PARAMETER Datastore
  The datastore(s) for which the partition info shall be
  returned. The parameter accepts a string or an object
  returned by the Get-Datastore cmdlet.
.EXAMPLE
  PS&gt; Get-VmfsPartitionInfo -Datastore &quot;DS*&quot;
.EXAMPLE
  PS&gt; Get-Datastore -Name &quot;DS1&quot; | Get-VmfsPartitionInfo
#&gt;
  param(
  [CmdletBinding()]
  [parameter(Mandatory = $true, ValueFromPipeline = $true)]
  [PSObject[]]$Datastore
  )

  process{
    foreach($ds in $Datastore){
      if($ds.getType().Name -eq &quot;string&quot;){
        $ds = Get-Datastore -Name $ds
      }
      $poweredHosts = $ds.ExtensionData.Host | %{Get-View -Id $_.Key} |
      where {$_.Runtime.PowerState -eq &quot;PoweredOn&quot;}
      $storSys = Get-View ($poweredHosts | Get-Random).ConfigManager.StorageSystem

      $ds.ExtensionData.Info.Vmfs.Extent | %{
        $devicePath = &quot;/vmfs/devices/disks/&quot; + $_.DiskName
        $storSys.RetrieveDiskPartitionInfo($devicePath) | %{
          New-Object PSObject -Property @{
            Name = $ds.Name
            Version = $ds.FileSystemVersion
            Device = $_.DeviceName
            PartitionFormat = $_.Spec.PartitionFormat
            BlockSizeMB = $ds.ExtensionData.Info.Vmfs.BlockSizeMb
            Blocks = $_.Layout.Total.Block
          }
        }
      }
    }
  }
}
</pre>
<span id="Annotations"><h4>Annotations</h4></span>
<p><strong>Line 25-27</strong>: A rather simple Object By Name implementation.</p>
<p><strong>Line 28-29</strong>: Collect the hosts, connected to the datastore, that are powered on. The reason is that we can&#8217;t use the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.host.StorageSystem.html#upgradeVmfs" target="_blank">UpgradeVmfs</a> method via the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.host.StorageSystem.html#upgradeVmfs" target="_blank">StorageSystem</a> of a powered off host.</p>
<p><strong>Line 31-36</strong>: Check if all the powered on and connected hosts support VMFS5. If not, leave the function.</p>
<p><strong>Line 37</strong>: Get the devicepath to the datastore.</p>
<p><strong>Line 38</strong>: Get the HostStorageSystem. Note that the function randomly selects 1 host from the powered on hosts. There is no real reason to do this, but I wanted to spread the method call over all available hosts.</p>
<p><strong>Line 40</strong>: Convert the datastore to VMFS5</p>
<p><strong>Line 68-70</strong>: Another example of my rather simple Object By Name implementation.</p>
<p><strong>Line 71-73</strong>: We randomly take 1 of the connected hosts to fetch the HostStorageSystem.</p>
<p><strong>Line 75</strong>: We loop through each VMFS extent of the datastore</p>
<p><strong>Line 76-77</strong>: The function uses the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.host.StorageSystem.html#retrieveDiskPartitionInfo" target="_blank">RetrieveDiskPartitionInfo</a> method to fetch the partition information.</p>
<p><strong>Line 78-85</strong>: The function fetches the information for each partition and puts it on the pipeline as a PSObject.</p>
<span id="Sample_usage"><h2>Sample usage</h2></span>
<p>In our vSphere 4 environment we have a number of VMFS3 datastores.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vmfs3-cli.png"><img class="alignnone wp-image-3777" title="vmfs3-cli" src="http://lucd.info/wp-content/uploads/2011/12/vmfs3-cli.png" alt="" width="524" height="112" /></a></p>
<p>First, I use the <strong>Get-VmfsPartition</strong> function to check the partitioninfo of each datastore.</p>
<pre class="brush: powershell; title: ; notranslate">

Get-Datastore DS* | Get-VmfsPartitionInfo | ft -AutoSize
</pre>
<p>The result.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vmfs3-partition-info.png"><img class="alignnone  wp-image-3783" title="vmfs3-partition-info" src="http://lucd.info/wp-content/uploads/2011/12/vmfs3-partition-info.png" alt="" width="600" height="102" /></a></p>
<p>Notice the <strong>BlockSizeMB</strong> column in the output, all 4 possible blocksizes for VMFS3 datastores are present.</p>
<p>Let&#8217;s upgrade these VMFS3 datastores to VMFS5 datastores.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-Datastore DS* | ConvertTo-Vmfs5
</pre>
<p>The convert function produces no output, but we can check what the new properties are with the <strong>Get-VmfsPartitionInfo</strong> function.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vmfs5-partition-info.png"><img class="alignnone  wp-image-3785" title="vmfs5-partition-info" src="http://lucd.info/wp-content/uploads/2011/12/vmfs5-partition-info.png" alt="" width="618" height="105" /></a></p>
<p>The VMFS version is <strong>5.54</strong>, so the conversion worked.</p>
<p>But the attentive viewer might have noticed a couple of values he didn&#8217;t expect.</p>
<ul>
<li>The PartitionFormat still says &#8216;MBR&#8217;. Shouldn&#8217;t that be &#8216;GPT&#8217; ?</li>
<li>The BlocksizeMB stayed the same as before the VMFS5 conversion. Shouldn&#8217;t that be 1MB for VMFS5 datastores ?</li>
</ul>
<p>The answer to both questions can be found in Cormac&#8217;s post called <a href="http://blogs.vmware.com/vsphere/2011/07/new-vsphere-50-storage-features-part-1-vmfs-5.html" target="_blank">vSphere 5.0 Storage Features Part 1 &#8211; VMFS-5</a>.</p>
<ul>
<li>A converted datastores keeps the &#8216;MBR&#8217; format until it grows bigger than 2TB.</li>
<li>A converted datastores keeps the original VMFS3 blocksize.</li>
</ul>
<p>And I want to repeat Cormac&#8217;s final advise in his post, if you have the luxury to do so, it&#8217;s better to create new VMFS5 datastores instead of converting VMFS3 datastores !</p>
<span id="VIProperty"><h2>VIProperty</h2></span>
<p>Derived from the <strong>Get-VmfsPartitionInfo</strong> function, I created a <strong>New-VIProperty</strong> definition to return the format of the first datastore partition.</p>
<pre class="brush: powershell; title: ; notranslate">
New-VIProperty -Name PartitionFormat -ObjectType Datastore `
  -Value {
    param($ds)

    $storSys = Get-View (Get-View $ds.ExtensionData.Host[0].Key).ConfigManager.StorageSystem
    $partInfo = $storSys.RetrieveDiskPartitionInfo(&quot;/vmfs/devices/disks/&quot; +
      $ds.ExtensionData.Info.Vmfs.Extent[0].DiskName)
    $partInfo[0].Spec.PartitionFormat
  } -Force | Out-Null
</pre>
<p>Note that you will only get the partition format (MBR or GPT) when you use this in a vSphere 5, or higher, environment. The <strong>partitionFormat</strong> property in the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.host.DiskPartitionInfo.Specification.html" target="_blank">HostDiskPartitionSpec</a> object is only available since API 5.</p>
<p>Enjoy !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/QgAjXoN87JI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2011/12/19/vsphere-5-top-10-vmfs5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2011/12/19/vsphere-5-top-10-vmfs5/</feedburner:origLink></item>
		<item>
		<title>vSphere 5 Top 10 – NetIOC</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/RJPKZSq7ho4/</link>
		<comments>http://www.lucd.info/2011/12/15/vsphere-5-top-10-netioc/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 21:16:42 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<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 number 5 in the Top-10, Network I/O Control. This feature allows user-defined network resource pools and end-to-end QoS. Note that this feature requires distributed Switches (dvSwitch). In fact I could have also written this post in my dvSwitch series with the title [...]]]></description>
			<content:encoded><![CDATA[<p>Another post from our <a href="http://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="http://www.lucd.info/tag/dvswitch/" target="_blank">dvSwitch series</a> with the title <strong>dvSwitch scripting – Part 10 – NetIOC</strong>.</p>
<span id="The_script"><h2><span id="more-3747"></span>The script</h2></span>
<pre class="brush: powershell; title: ; notranslate">
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>
<span id="Annotations"><h4>Annotations</h4></span>
<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>
<span id="Sample_usage"><h2>Sample usage</h2></span>
<p>We start with an empty dvSwitch. The Get-dvSwitch function can be found in my <a href="http://www.lucd.info/2009/10/12/dvswitch-scripting-part-2-dvportgroup/" target="_blank">dvSwitch scripting – Part 2 – dvPortgroup</a> post.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/NETIOC-initial.png"><img class="alignnone size-full wp-image-3754" title="NETIOC-initial" src="http://lucd.info/wp-content/uploads/2011/12/NETIOC-initial.png" alt="" width="490" height="196" /></a></p>
<p>First we get the dvSwitch and we get a list of the current network resource pools.</p>
<pre class="brush: powershell; title: ; notranslate">
$dvSw = Get-dvSwitch -DatacenterName &quot;DC1&quot; -dvSwitchName &quot;dvSw1&quot;
Get-dvSwNetworkResourcePool -dvSw $dvSw | ft -AutoSize
</pre>
<p>This will return the system network resource pools.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system-cli.png"><img class="alignnone size-full wp-image-3755" title="NETIOC-respools-system-cli" src="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system-cli.png" alt="" width="620" height="135" /></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="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system2.png"><img class="alignnone size-full wp-image-3758" title="NETIOC-respools-system" src="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-system2.png" alt="" width="626" height="302" /></a></p>
<p>Next we create a number of user-defined network resource pools.</p>
<pre class="brush: powershell; title: ; notranslate">
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>The result shows the 3 newly created network resource pools.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user.png"><img class="alignnone size-full wp-image-3759" title="NETIOC-respools-user" src="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user.png" alt="" width="634" height="177" /></a></p>
<p>And we see the same in the vSphere Client.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-VC.png"><img class="alignnone size-full wp-image-3761" title="NETIOC-respools-user-VC" src="http://lucd.info/wp-content/uploads/2011/12/NETIOC-respools-user-VC.png" alt="" width="630" height="342" /></a></p>
<p>As we noticed earlier, NetIOC is not enabled by default. Let&#8217;s display the current setting.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-dvSwSIOC -dvSw $dvSw | ft -AutoSize
</pre>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/NetIOC-disabled.png"><img class="alignnone size-full wp-image-3760" title="NetIOC-disabled" src="http://lucd.info/wp-content/uploads/2011/12/NetIOC-disabled.png" alt="" width="306" height="66" /></a></p>
<p>We change the setting and retrieve the value again</p>
<pre class="brush: powershell; title: ; notranslate">
Set-dvSwSIOC -dvSw $dvSw -Enabled
Get-dvSwSIOC -dvSw $dvSw | ft -AutoSize
</pre>
<p>This gives</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/NetIOC-enabled.png"><img class="alignnone size-full wp-image-3762" title="NetIOC-enabled" src="http://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>
<pre class="brush: powershell; title: ; notranslate">
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>Enjoy !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/RJPKZSq7ho4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2011/12/15/vsphere-5-top-10-netioc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2011/12/15/vsphere-5-top-10-netioc/</feedburner:origLink></item>
		<item>
		<title>vSphere 5 Top 10 – vMotion</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/icwydd0hZE0/</link>
		<comments>http://www.lucd.info/2011/12/15/vsphere-5-top-10-vmotion/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 23:12:36 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[2011]]></category>
		<category><![CDATA[Dutch]]></category>
		<category><![CDATA[multi-nic]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[vMotion]]></category>
		<category><![CDATA[VMUG]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[PowerCLI]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3734</guid>
		<description><![CDATA[Another post coming from our Dutch VMUG Event 2011 presentation. On position number 10, we find the vMotion Enhancements that were introduced with vSphere 5. A single vMotion can now scale over multiple NICs. This feature can use a regular vSwitch or distributed vSwitch.On YouTube there are 2 videos, uploaded by VMwareKB, that show how [...]]]></description>
			<content:encoded><![CDATA[<p>Another post coming from our <a href="http://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>. On position number <strong>10</strong>, we find the <strong>vMotion Enhancements</strong> that were introduced with <strong>vSphere 5</strong>.</p>
<p>A single vMotion can now<strong> scale</strong> over multiple NICs. This feature can use a <strong>regular vSwitch</strong> or <strong>distributed vSwitch</strong>.On YouTube there are 2 videos, uploaded by <a href="http://www.youtube.com/user/VMwareKB" target="_blank">VMwareKB</a>, that show how to configure such a vMotion enabled multi-NIC vSwitch, <a href="http://www.youtube.com/watch?v=7njBRF2N0Z8" target="_blank">regular</a> and <a href="http://www.youtube.com/watch?v=n-XBof_K-b0" target="_blank">distributed</a>.</p>
<p>Very useful videos, but as you can imagine, I wanted to automate this. No GUI clicking for me  <img src='http://lucd.info/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><span id="more-3734"></span></p>
<span id="The_script"><h2>The script</h2></span>
<pre class="brush: powershell; title: ; notranslate">
function Set-vMotionMultiNic{
&lt;#
.SYNOPSIS  Configure multi-NIC vMotion
.DESCRIPTION The function will configure multi-NIC vMotion
  enabled portgroups on a regular vSwitch
.NOTES  Author:  Luc Dekens
.PARAMETER VMHost
  The ESXi host where the vMotion enabled portgroups shall be
  configured.
  The parameter accepts a string or the object returned by the
  Get-VMHost cmdlet.
.PARAMETER VirtualSwitch
  The virtual switch on which the vMotion enabled portgroups
  shall be configured.
  The parameter accepts a string or the object returned by the
  Get-VirtualSwitch cmdlet.
.PARAMETER pNic
  An array with the vnics that shall be used to configure the
  portgroups. Depending on the number of provided vnics, the
  function will create the optimal number of portgroups.
  The arrays on pNic, IPaddress and SubnetMask shall have the
  same number of elements.
.PARAMETER IpAddress
  An array with the IP addresses that shall be used on the
  portgroups
.PARAMETER SubnetMask
  An array with the subnetmasks.
.EXAMPLE
  PS&gt; Set-vMotionMultiNic -VMHost MyESX -VSwitch MyvSw `
  PS&gt;&gt;   -pNic &quot;vmnic2&quot;,&quot;vmnic3&quot;,&quot;vmnic4&quot; `
  PS&gt;&gt;   -IpAddress &quot;192.168.1.1&quot;,&quot;192.168.1.2&quot;,&quot;192.168.1.3&quot; `
  PS&gt;&gt;   -SubnetMask (,&quot;255.255.255.0&quot; * 3)
#&gt;
  param(
    [psobject]$VMHost,
    [psobject]$VirtualSwitch,
    [string[]]$pNic,
    [string[]]$IpAddress,
    [string[]]$SubnetMask
  )56

  if($VMHost.getType().Name -eq &quot;string&quot;){
    $VMHost = Get-VMHost -Name $VMHost
  }
  if($VMHost.ApiVersion.Split('.')[0] -lt 5){
    Write-Warning &quot;MultiNic for vMotion requires at least ESXi 5.0&quot;
    exit
  }

  if($VirtualSwitch.getType().Name -eq &quot;string&quot;){
    $VirtualSwitch = $VMHost | Get-VirtualSwitch -Name $VirtualSwitch
  }
  $indices = 0..($pNic.Count - 1)
  foreach($i in $indices){
    $pg = New-VirtualPortGroup -Name (&quot;vMotion-{0:d2}&quot; -f ($i + 1)) -VirtualSwitch $VirtualSwitch
    New-VMHostNetworkAdapter -VMHost $VMHost -VirtualSwitch $VirtualSwitch -PortGroup $pg -IP $IpAddress[$i] -SubnetMask $SubnetMask[$i] -VMotionEnabled:$true | Out-Null
    Get-NicTeamingPolicy -VirtualPortGroup $pg |
    Set-NicTeamingPolicy -MakeNicActive $pNic[$i] -MakeNicStandby $pNic[($indices | where {$_ -ne $i})] |Out-Null
  }
}
</pre>
<span id="Annotations"><h4>Annotations</h4></span>
<p><strong>Line 42-44</strong>: A simple Object By Name (OBN) implementation for the ESXi host</p>
<p><strong>Line 45-48</strong>: A check if we are configuring this for at least a vSphere 5 server</p>
<p><strong>Line 50-52</strong>: A simple Object By Name (OBN) implementation for the regular vSwitch</p>
<p><strong>Line 53</strong>: When the function is called with &#8216;n&#8217; vnics, it will have to create &#8216;n&#8217; portgroups. This calculation creates the list of suffixes that will be used on the portgroup names.</p>
<p><strong>Line 55</strong>: The creation of the portgroup. Note how the function adds a 2 digit suffix with the -format operator to the basename (&#8216;vMotion&#8217;)</p>
<p><strong>Line 56</strong>: Set the IP address and subnetmask</p>
<p><strong>Line 57-58</strong>: The Teaming is configured in the same way the VMwareKB video demonstrates.</p>
<span id="Sample_use"><h2>Sample use</h2></span>
<p>To demonstrate the function, I will use a simple configuration. We have 1 regular vSwitch that has 3 vnics connected to it.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vMotion-vsw-before.png"><img class="alignnone size-full wp-image-3740" title="vMotion-vsw-before" src="http://lucd.info/wp-content/uploads/2011/12/vMotion-vsw-before.png" alt="" width="476" height="172" /></a></p>
<p>We call the function</p>
<pre class="brush: powershell; title: ; notranslate">
$IP = &quot;192.168.0.210&quot;,&quot;192.168.0.211&quot;,&quot;192.168.0.212&quot;
$MASK = &quot;255.255.255.0&quot;,&quot;255.255.255.0&quot;,&quot;255.255.255.0&quot;
$NIC = &quot;vmnic1&quot;,&quot;vmnic2&quot;,&quot;vmnic3&quot;

Set-vMotionMultiNic -VMHost 192.168.0.107 -VirtualSwitch vSwitch1 -pNic $NIC -IPAddress $IP -SubnetMask $MASK
</pre>
<p>The function creates the vMotion portgroups (in the same way as the VMwareKB video shows).</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vMotion-vsw-after.png"><img class="alignnone size-full wp-image-3742" title="vMotion-vsw-after" src="http://lucd.info/wp-content/uploads/2011/12/vMotion-vsw-after.png" alt="" width="587" height="222" /></a></p>
<p>And each of these vMotion enabled portgroups is configured similar to the method shown in the video.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/vMotion-vsw-detail.png"><img class="alignnone size-full wp-image-3743" title="vMotion-vsw-detail" src="http://lucd.info/wp-content/uploads/2011/12/vMotion-vsw-detail.png" alt="" width="254" height="439" /></a></p>
<p>In a following post I will show how this can be done for a dvSwitch.</p>
<p>Enjoy !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/icwydd0hZE0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2011/12/15/vsphere-5-top-10-vmotion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2011/12/15/vsphere-5-top-10-vmotion/</feedburner:origLink></item>
		<item>
		<title>vSphere 5 Top 10 – HA</title>
		<link>http://feedproxy.google.com/~r/LucdNotes/~3/Zmwpkmrqhy0/</link>
		<comments>http://www.lucd.info/2011/12/13/vsphere-5-top-10-%e2%80%93-ha/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 21:22:15 +0000</pubDate>
		<dc:creator>LucD</dc:creator>
				<category><![CDATA[2011]]></category>
		<category><![CDATA[datastore]]></category>
		<category><![CDATA[Dutch]]></category>
		<category><![CDATA[HA]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[VMUG]]></category>
		<category><![CDATA[vSphere]]></category>

		<guid isPermaLink="false">http://www.lucd.info/?p=3715</guid>
		<description><![CDATA[The second post originating from our presentation at the Dutch VMUG Event 2011 is about HA. vSphere High Availability appeared in the 2nd place of the vSphere 5 features Top 10. For the HA feature we showed how you could find out the FDM master and slaves in your cluster, and how to find the [...]]]></description>
			<content:encoded><![CDATA[<p>The second post originating from our presentation at the <a href="http://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</a> is about HA. vSphere <strong>High Availability</strong> appeared in the 2nd place of the <strong>vSphere 5 features Top 10</strong>. For the HA feature we showed how you could find out the <strong>FDM</strong> master and slaves in your cluster, and how to find the <strong>heartbeat datastore</strong>.</p>
<p style="padding-left: 150px;"><a href="http://lucd.info/wp-content/uploads/2011/12/FDM.jpg"><img class="alignnone size-full wp-image-3716" title="FDM" src="http://lucd.info/wp-content/uploads/2011/12/FDM.jpg" alt="" width="234" height="291" /></a></p>
<span id="The_FDM_roles"><h2><span id="more-3715"></span>The FDM roles</h2></span>
<p>The following script will show,for each cluster node, which FDM role it holds.</p>
<pre class="brush: powershell; title: ; notranslate">
function Get-DasHostState{
  param(
  [PSObject]$Cluster
  )

  if($Cluster.GetType().Name -eq &quot;string&quot;){
    $Cluster = Get-Cluster -Name $Cluster
  }
  Get-View -ViewType HostSystem -Property Name,Runtime.DasHostState | %{
    New-Object PSObject -Property @{
      VMHost = $_.Name
      DasHostState = $_.RunTime.DasHostState.State
      StateReporter = (Get-View -Id $_.RunTime.DasHostState.StateReporter -Property Name).Name
    }
  }
}
</pre>
<p>To call the function you can pass a clustername or the output of a Get-Cluster cmdlet. Something like this.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-DasHostState -Cluster Cluster1
</pre>
<p>or this</p>
<pre class="brush: powershell; title: ; notranslate">
$clus = Get-Cluster -Name Cluster1
Get-DasHostState -Cluster $clus
</pre>
<p>The output looks like this</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/HA-FDM-report.png"><img class="alignnone size-full wp-image-3718" title="HA-FDM-report" src="http://lucd.info/wp-content/uploads/2011/12/HA-FDM-report.png" alt="" width="582" height="88" /></a></p>
<p>Note that there are more <strong>DasHostState</strong> values, besides <strong>master</strong> and <strong>connectedToMaster</strong>, possible. The complete list can be found in the <a href="http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.cluster.DasFdmAvailabilityState.html" target="_blank">ClusterDasFdmAvailabilityState</a> enumeration.</p>
<p>And you can of course provide this functionality as a New-VIProperty.</p>
<pre class="brush: powershell; title: ; notranslate">
New-VIProperty -Name &quot;DasHostState&quot; -ObjectType Cluster -Value {
  param($cluster)

  Get-View $cluster.ExtensionData.Host -Property Name,Runtime.DasHostState | %{
    New-Object PSObject -Property @{
      VMHost = $_.Name
      DasHostState = $_.RunTime.DasHostState.State
      StateReporter = (Get-View -Id $_.RunTime.DasHostState.StateReporter).Name
    }
  }
} -Force | Out-Null
</pre>
<p>Now you can find the FDM states with a call like this</p>
<pre class="brush: powershell; title: ; notranslate">
Get-Cluster -Name London | Select -ExpandProperty DasHostState
</pre>
<p>The output will look exactly the same as the output that comes out of the Get-DasHostState function.</p>
<span id="The_heartbeat_datastore"><h2>The heartbeat datastore</h2></span>
<p>Another HA novelty in vSphere 5 is that it will now use, besides a network-based heartbeat, a datastore heartbeat, to check the presence of the nodes. To find out which of the shared datastores is used as the heartbeat datastore, you can use the following function.</p>
<pre class="brush: powershell; title: ; notranslate">
function Get-DasHostState{
  param(
  [PSObject]$Cluster
  )

  if($Cluster.GetType().Name -eq &quot;string&quot;){
    $Cluster = Get-Cluster -Name $Cluster
  }

  $cluster.ExtensionData.RetrieveDasAdvancedRuntimeInfo()  | %{
    $_.HeartbeatDatastoreInfo | %{
      New-Object PSObject -Property @{
        Datastore = (Get-View -Id $_.Datastore).Name
        VMHosts = [string]::Join(',',($_.Hosts | %{(Get-View -Id $_).Name}))
      }
    }
  }
}
</pre>
<p>The function can be called again with the name of a cluster or with the object returned by the Get-Cluster cmdlet.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-DasHostState -Cluster Cluster1
</pre>
<p>The output looks something like this.</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/HA-DS-report.png"><img class="alignnone size-full wp-image-3727" title="HA-DS-report" src="http://lucd.info/wp-content/uploads/2011/12/HA-DS-report.png" alt="" width="452" height="62" /></a></p>
<p>And of course, the same functionality as a New-VIProperty.</p>
<pre class="brush: powershell; title: ; notranslate">
New-VIProperty -Name HeartbeatDatastore -ObjectType Cluster -Value {
  param($cluster)

  $cluster.ExtensionData.RetrieveDasAdvancedRuntimeInfo() | %{
    [String]::Join(',',($_.HeartbeatDatastoreInfo |
    %{(Get-View -Id $_.Datastore).Name}))
  }
} -Force | Out-Null
</pre>
<p>You can now use the <strong>HeartbeatDatastore</strong> property to get the datastore that is used for the heartbeat.</p>
<pre class="brush: powershell; title: ; notranslate">
Get-Cluster -Name Cluster1 | Select Name, HeartbeatDatastore
</pre>
<p>Which will result in</p>
<p><a href="http://lucd.info/wp-content/uploads/2011/12/HA-DS-New-VIProperty-report.png"><img class="alignnone size-full wp-image-3730" title="HA-DS-New-VIProperty-report" src="http://lucd.info/wp-content/uploads/2011/12/HA-DS-New-VIProperty-report.png" alt="" width="597" height="71" /></a></p>
<p>Enjoy !</p>
<img src="http://feeds.feedburner.com/~r/LucdNotes/~4/Zmwpkmrqhy0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.lucd.info/2011/12/13/vsphere-5-top-10-%e2%80%93-ha/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.lucd.info/2011/12/13/vsphere-5-top-10-%e2%80%93-ha/</feedburner:origLink></item>
	</channel>
</rss>

