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

<channel>
	<title>VMDK Archives - LucD notes</title>
	<atom:link href="https://www.lucd.info/tag/vmdk/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.lucd.info/tag/vmdk/</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Wed, 08 Apr 2020 11:02:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.10</generator>

<image>
	<url>https://www.lucd.info/wp-content/uploads/2018/12/cropped-120px-Tibetan_Dharmacakra-32x32.png</url>
	<title>VMDK Archives - LucD notes</title>
	<link>https://www.lucd.info/tag/vmdk/</link>
	<width>32</width>
	<height>32</height>
</image> 
<atom:link rel="hub" href="https://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="https://pubsubhubbub.superfeedr.com"/><atom:link rel="hub" href="https://websubhub.com/hub"/>	<item>
		<title>Monitor the size of your vDisks</title>
		<link>https://www.lucd.info/2012/12/02/monitor-the-size-of-your-vdisks/</link>
					<comments>https://www.lucd.info/2012/12/02/monitor-the-size-of-your-vdisks/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 02 Dec 2012 21:31:48 +0000</pubDate>
				<category><![CDATA[datastore]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[statistics]]></category>
		<category><![CDATA[Thin Provisioning]]></category>
		<category><![CDATA[VMDK]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=4232</guid>

					<description><![CDATA[In a recent thread on the VMTN PowerCLI Community someone asked if it [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In a recent <a href="https://communities.vmware.com/message/2154603#2154603" target="_blank">thread</a> on the <a href="https://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli?view=discussions" target="_blank">VMTN PowerCLI Community</a> someone asked if it is possible to get <strong>historical hard disk statistics</strong>. I referred the user to my <a href="https://www.lucd.info/2011/06/19/datastore-usage-statistics/" target="_blank">Datastore usage statistics</a> post, where I showed how to use the &#8220;<em>disk</em>&#8221; metrics to get that information.</p>
<p>But getting the individual vDisk statistics is a bit more tricky compared to getting the datastore statistics, as I showed in that post. The &#8220;<em>disk</em>&#8221; metrics hold the information, but the <strong>Instance</strong> that points to the <strong>MoRef value</strong> of a VM makes it a bit more tricky to retrieve.</p>
<p>Be <span style="background-color: #ffff00;">forewarned</span>, the &#8220;<em>disk</em>&#8221; metrics hold usage data for <strong>all</strong> the vDisks that a specific VM has on a <strong>specific datastore</strong>. You will <strong>not</strong> be able to get <strong>individual</strong> vDisk statistics, unless the vDisks are stored on different datastores !</p>
<p>On the positive side, the &#8220;<em>disk</em>&#8221; metrics will allow you to see how your vDisks increase in size over time. For your Thick vDisks that increase will be by <strong>expanding</strong> them, and for your Thin vDisks it will also show the natural <strong>growth</strong>.</p>
<p><span id="more-4232"></span></p>
<h2>The Script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$datastoreName = &quot;MyDS&quot;
$targetVM = &quot;VM1&quot;,&quot;VM2&quot;,&quot;VM3&quot;
$monthsBack = 3
$interval = &quot;HI4&quot;

$ds = (Get-Datastore -Name $datastoreName).ExtensionData
$metric = &quot;disk.used.latest&quot;
$start = (Get-Date).AddMonths(-$monthsBack)

$vmTab = @{}

$localCulture = Get-Culture

Get-VM -Name $targetVM | %{
  $vmTab.Add($_.Id.Split('-')[2],$_.Name)
}

&amp;{Get-Stat2 -entity $ds -interval $interval -stat $metric -QueryInstances |
  where {$_.Instance -match &quot;^\d+$&quot; -and $vmTab.ContainsKey($_.Instance)} | %{
    Get-Stat2 -entity $ds -Instance $_.Instance -stat $metric -interval $interval -Start $start |
    Select @{N=&quot;VM&quot;;E={$vmTab[$_.Instance]}},Timestamp,Entity,Value,Unit,Interval
  }
} |
Group-Object -Property Timestamp | ForEach-Object -Process {
  $newObj = New-Object PSObject -Property @{
    Timestamp = [datetime]::Parse($_.Name,$localCulture)
  }
  $_.Group | %{
    Add-Member -InputObject $newObj -Name $_.VM -Value ($_.Value/1MB) -MemberType NoteProperty
  }
  $newObj
} |
Sort-Object -Property Timestamp |
Export-Csv &quot;C:\vdisk.csv&quot; -NoTypeInformation -UseCulture</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 1</strong>: The datastore for which the script will produce a report</p>
<p><strong> Line 2</strong>: The script looks for specific VMs on the datastore</p>
<p><strong>Line 4</strong>: The <strong>Historical Interval 4</strong> holds 1 entry per day, which is sufficient for monitoring vDisk growth. If you need finer samples change it to another Historical Interval, but note that the &#8220;<em>disk</em>&#8221; metrics are only available for the historical intervals.</p>
<p><strong>Line 12</strong>: This will allow the script to interpret dates correctly, in other words it allows the script later on to read dates in the format &#8220;mm/dd/yyyy&#8221; and in the &#8220;dd/mm/yyyy&#8221; format.</p>
<p><strong>Line 14-16</strong>: For the VMs we want to report upon, the script fetches the <strong>Value</strong> property of its <strong>MoRef</strong>. This Value corresponds with the Instance that will be returned with the performance data, and that allows the script to link the Instance to the VM name.</p>
<p><strong>Line 18-19</strong>: With the <strong>QueryInstances</strong> parameter the script requests all the available <strong>Instances</strong>, in other words VM specific performance data. The script checks if the <strong>Instance</strong> is in the <strong>MoRef.Value</strong> format and if the Instance corresponds with one of the VMs we want to report upon.</p>
<p><strong>Line 20-21</strong>: For all the qualifying <strong>Instances</strong> the script fetches the performance data.</p>
<p><strong>Line 24-32</strong>: The performance data is grouped on the <strong>Timestamp</strong>. All the individual performance objects with a specific Timestamp, each for 1 Instance (or 1 VM), are combined into 1 object with a <strong>property</strong> for each Instance.</p>
<p><strong>Line 26</strong>: The <strong>Timestamp</strong> became a string, in a format defined by the <strong>locale</strong>, in the <strong>Group-Object</strong> earlier on. To interpret the date string correctly the script calls the <strong>Parse</strong> method and passes the locale object.</p>
<h2>Sample Usage</h2>
<p>The script uses my <strong>Get-Stat2</strong> function I have used before. Make sure that function is known before calling the script above. The latest version of my <strong>Get-Stat2</strong> function can be downloaded below.</p>
<p>[wpfilebase tag=file id=11]</p>
<p>The CSV file that is produced by the script looks like this:</p>
<p><img fetchpriority="high" decoding="async" class="wp-image-4234 alignnone" title="vdisk-stats-1" src="https://lucd.info/wp-content/uploads/2012/12/vdisk-stats-1.png" alt="" width="657" height="279" srcset="https://www.lucd.info/wp-content/uploads/2012/12/vdisk-stats-1.png 730w, https://www.lucd.info/wp-content/uploads/2012/12/vdisk-stats-1-300x127.png 300w" sizes="(max-width: 657px) 100vw, 657px" /></p>
<p>If you have a PowerShell module or snapin that allows you to produce graphs, you can make the result a bit fancier.</p>
<p>I replaced the <strong>Export-Csv</strong> line with the <strong>Out-Chart</strong> cmdlet from <a href="https://www.softwarefx.com/sfxSqlProducts/powerGadgets/default.aspx" target="_blank">PowerGadgets</a>.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Out-Chart -Gallery Lines `
  -AllSeries_MarkerSize 0 `
  -Title &quot;vDisk monitoring&quot; `
  -AxisX_Title_Text &quot;Date&quot; `
  -AxisY_Title_Text &quot;Space (GB)&quot; `
  -Values $targetVM `
  -Label {([datetime]::Parse($_.Timestamp,$localCulture)).ToString(&quot;dd-MM&quot;)}</pre><p></p>
<p>Notice how I use the Parse method to interpret the dates correctly for the locale where the script runs.<br />
The resulting picture looks as follows.</p>
<p><img decoding="async" class="alignnone  wp-image-4236" title="vdisk-stats-2" src="https://lucd.info/wp-content/uploads/2012/12/vdisk-stats-2.png" alt="" width="625" height="346" srcset="https://www.lucd.info/wp-content/uploads/2012/12/vdisk-stats-2.png 781w, https://www.lucd.info/wp-content/uploads/2012/12/vdisk-stats-2-300x165.png 300w" sizes="(max-width: 625px) 100vw, 625px" /></p>
<p>This vDisk reporting script can be expanded in many ways. We could for example find all created and removed VMs, which would give us a complete report of which VMs have hsitorically been using your datastore space. But that will be for a later post.</p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2012/12/02/monitor-the-size-of-your-vdisks/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Storage Views &#8211; Datastores</title>
		<link>https://www.lucd.info/2011/11/14/storage-views-datastores/</link>
					<comments>https://www.lucd.info/2011/11/14/storage-views-datastores/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Mon, 14 Nov 2011 19:58:06 +0000</pubDate>
				<category><![CDATA[datastore]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Storage Views]]></category>
		<category><![CDATA[VMDK]]></category>
		<category><![CDATA[report]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3651</guid>

					<description><![CDATA[In the vCenter Client, since vSphere 4, you can find a Storage Views [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In the vCenter Client, since <strong>vSphere 4</strong>, you can find a <strong>Storage Views</strong> tab on several of the VI containers. The data in these Storage Views is collected and provided by the <strong>vCenter Storage Monitoring</strong> plug-in.</p>
<p>Have a look at <a href="https://www.twitter.com/davidmdavis" target="_blank" rel="noopener noreferrer">David Davis</a>&#8216;s post, called <a href="http://www.virtualizationadmin.com/articles-tutorials/vmware-esx-and-vsphere-articles/storage-management/using-vmware-vsphere-storage-views.html" target="_blank" rel="noopener noreferrer">Using VMware vSphere Storage Views</a>, for more information on what you can do with the Storage Views.</p>
<p>Some time ago I got a question from Andrew how the <strong>Multipathing Status</strong> presented in the Storage Views could be detected and reported upon by a PowerCLI script. What looked rather simple at first, turned out to be a bit more difficult than I anticipated.</p>
<p><span id="more-3651"></span></p>
<p>The primary reason I created this function, is that it will allow to schedule the creation of the Storage Views &#8211; Datastores values at regular intervals. A feature that is unfortunately missing from the vCenter Client plug-in.</p>
<p>With those saved values it is easy to produce reports that show who is consuming the storage over time.</p>
<h2>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Get-StorageViewDatastore{
&lt;#
.SYNOPSIS  Retrieve the &quot;Storage Views - Show all Datastores&quot; values
.DESCRIPTION The function calculates and returns all the values
  that you get in the Storage Views - Show all Datastores panel.
.NOTES  Author:  Luc Dekens
.PARAMETER VMHost
  Specify the ESX(i) server for which you want to retrieve
  the Storage Views values.
.PARAMETER Cluster
  Specify the Cluster for which you want to retrieve
  the Storage Views values.
.PARAMETER Datacenter
  Specify the Datacenter for which you want to retrieve
  the Storage Views values.
.PARAMETER VM
  Specify the VM for which you want to retrieve
  the Storage Views values.
.PARAMETER ResourcePool
  Specify the ResourcePool for which you want to retrieve
  the Storage Views values.
.EXAMPLE
  PS&gt; Get-StorageViewDatastore -VMHost MyCluster
.EXAMPLE
  PS&gt; Get-Datacenter MyDC | Get-StorageViewDatastore
#&gt;

  [CmdletBinding()]
  param(
  [parameter(ParameterSetName=&quot;VMHost&quot;,Mandatory = $true)]
  [PSObject]$VMHost,
  [parameter(ParameterSetName=&quot;Cluster&quot;,Mandatory = $true)]
  [PSObject]$Cluster,
  [parameter(ParameterSetName=&quot;Datacenter&quot;,Mandatory = $true)]
  [PSObject]$Datacenter,
  [parameter(ParameterSetName=&quot;VM&quot;,Mandatory = $true)]
  [PSObject]$VM,
  [parameter(ParameterSetName=&quot;ResourcePool&quot;,Mandatory = $true)]
  [PSObject]$ResourcePool
  )

  process{
    # Get the datastores and ESX(i) servers
    switch($PSCmdlet.ParameterSetName){
      &quot;Datacenter&quot; {
        if($Datacenter.GetType().Name -eq &quot;String&quot;){
          $Datacenter = Get-Datacenter -Name $Datacenter
        }
        $vms = Get-VM -Location $Datacenter
        $esx = Get-VMHost -Location $Datacenter
        $datastores = Get-Datastore -VMHost $esx
      }
      &quot;Cluster&quot; {
        if($Cluster.GetType().Name -eq &quot;String&quot;){
          $Cluster = Get-Cluster -Name $Cluster
        }
        $vms = Get-VM -Location $cluster
        $esx = Get-VMHost -Location $Cluster
        $datastores = Get-Datastore -VMHost $esx
      }
      &quot;VMHost&quot; {
        if($VMHost.GetType().Name -eq &quot;String&quot;){
          $VMHost = Get-VMHost -Name $VMHost
        }
        $vms = Get-VM -Location $VMHost
        $esx = $VMHost
        $datastores = Get-Datastore -VMHost $VMHost
      }
      &quot;VM&quot; {
        if($VM.GetType().Name -eq &quot;String&quot;){
          $VM = Get-VM -Name $VM
        }
        $vms = $vm
        $esx = $vm.VMHost
        $datastores = Get-Datastore -Name ($vms | Get-HardDisk -DiskType flat | %{$_.Filename.Split(']')[0].TrimStart('[')} | Sort-Object -Unique) | Sort-Object -Property Name
      }
      &quot;ResourcePool&quot; {
        if($ResourcePool.GetType().Name -eq &quot;String&quot;){
          $ResourcePool = Get-ResourcePool -Name $ResourcePool
        }
        $vms = Get-VM -Location $ResourcePool
        $esx = $vms  | %{$_.VMHost} | Sort-Object -Property Name -Unique
        $datastores = Get-Datastore -Name ($vms | Get-HardDisk -DiskType flat | %{$_.Filename.Split(']')[0].TrimStart('[')} | Sort-Object -Unique) | Sort-Object -Property Name
      }
    }

    # Create some helper collections
    $esxMoRef = $esx | %{$_.ExtensionData.MoRef}
    $vmMoRef = $vms | %{$_.ExtensionData.MoRef}

    # Set up a HBA hash table
    $hbaFCNodeWWN = @{}
    Get-VMHostHba -VMHost $esx -Type FibreChannel | %{
      $hbaFCNodeWWN[&quot;{0:X}&quot; -f $_.NodeWorldWideName] = 0
    }

    # Handle all datastores
    foreach($ds in $datastores){
      $mpStatus = $usedSpace = $snapSpace = &quot;&quot;
      if($ds.Type -eq &quot;VMFS&quot;){
        $lun = $ds.ExtensionData.Info.Vmfs.Extent | %{$_.DiskName} |
          %{Get-ScsiLun -CanonicalName $_ -VmHost $esx -ErrorAction SilentlyContinue}
        $hbaFCCopy = $hbaFCNodeWWN.Clone()
        # Count Active and Standby paths
        # If there are 2 or more paths, the multi-path status is fully redundant
        Get-ScsiLunPath -ScsiLun $lun | where {&quot;Active&quot; ,&quot;Standby&quot; -contains $_.State} | %{
          $hbaFCCopy[$_.LunPath.Split(':')[0].Split('.')[1]] += 1
        }
        if(($hbaFCCopy.Values | where {$_} | Measure-Object).Count -gt 1){
          $mpStatus = &quot;Full Redundancy&quot;
        }
        else{
          $mpStatus = &quot;Partial/No Redundancy&quot;
        }
      }

      # Get the total used, snapshot, swap, shared and other space
      $usedSpace = 0
      $snapSpace = 0
      $vdiskSpace = 0
      $swapSpace = 0
      $otherSpace = 0
      $sharedSpace = 0
      if($ds.ExtensionData.Vm){
        Get-View $ds.ExtensionData.Vm | where {$vmMoRef -contains $_.MoRef -and $esxMoRef -contains $_.Runtime.Host} | %{
          $snapIndex = @()
          $dsPattern = '\[' + $ds.Name + '\]'
          $usedSpace += ($_.Storage.PerDatastoreUsage | where {$_.Datastore -eq $ds.ExtensionData.MoRef}).Committed
          if($_.LayoutEx.Snapshot){
            $snapIndex = $_.layoutEx.Disk | %{$_.Chain[1..($_.Chain.Count - 1)]} | %{$_.FileKey}
          }
          $snapIndex += $_.layoutEx.File | where {&quot;snapshotList&quot;,&quot;snapshotData&quot; -contains $_.Type -and $_.Name -match $dsPattern} | %{$_.Key}
          if($snapIndex){
            $snapSpace += ($_.LayoutEx.File | where {$snapIndex -contains $_.Key -and $_.Name -match $ds.Name} | Measure-Object -Property Size -Sum).Sum
          }
          $vdiskIndex = $_.layoutEx.File | where {&quot;diskDescriptor&quot;,&quot;diskExtent&quot; -contains $_.Type -and $_.Name -match $dsPattern} | %{$_.Key}
          if($vdiskIndex){
            $vdiskSpace += ($_.LayoutEx.File | where {$vdiskIndex -contains $_.Key} | Measure-Object -Property Size -Sum).Sum
          }
          $swapIndex = $_.LayoutEx.File | where {$_.Type -eq &quot;swap&quot; -and $_.Name -match $dsPattern} | %{$_.Key}
          if($swapIndex){
            $swapSpace += ($_.LayoutEx.File | where {$swapIndex -contains $_.Key} | Measure-Object -Property Size -Sum).Sum
          }
          $otherIndex = $_.LayoutEx.File | where {&quot;log&quot;,&quot;config&quot;,&quot;extendedConfig&quot;,&quot;nvram&quot;,&quot;core&quot; -contains $_.Type -and $_.Name -match $dsPattern} | %{$_.Key}
          if($otherIndex){
            $otherSpace += ($_.LayoutEx.File | where {$otherIndex -contains $_.Key} | Measure-Object -Property Size -Sum).Sum
          }
          $vmds = $_.Storage.PerDatastoreUsage | where {$_.Datastore -eq $ds.ExtensionData.MoRef}
          if($vmds){
            $sharedSpace += ($vmds.Committed - $vmds.Unshared)
          }
        }
      }

      # Collect all values for Storage Views - Datastores
      New-Object PSObject -Property @{
        VMHost = $esx.Name
        Datastore = $ds.Name
        &quot;File System Type&quot; = $ds.Type.Replace(&quot;NFS&quot;,&quot;NAS&quot;)
        &quot;Connectivity Status&quot; = &amp;{if($ds.Accessible){&quot;Up&quot;}else{&quot;Down&quot;}}
        &quot;Multipathing Status&quot; = $mpStatus
        Capacity = Get-FriendlyUnit -Value ($ds.CapacityMB * 1MB)
        Free = Get-FriendlyUnit -Value ($ds.FreeSpaceMB * 1MB)
        Used = Get-FriendlyUnit -Value $usedSpace
        Snapshot = Get-FriendlyUnit -Value $snapSpace
        vDisk = Get-FriendlyUnit -Value ($vdiskSpace - $snapSpace)
        Swap = Get-FriendlyUnit -Value $swapSpace
        Other = Get-FriendlyUnit -Value $otherSpace
        Shared = Get-FriendlyUnit -Value $sharedSpace
      }
    }
  }
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 29-40</strong>: The function uses <strong>5 parameter sets</strong> that allow you to get the Storage Views &#8211; Datastores values for a VM, an ESX(i) server, a ResourcePool, a Cluster or a Datacenter.</p>
<p><strong>Line 44-85</strong>: For each of the parameter sets, this Switch block calculates the VMs, the ESX(i) host(s) and the datastore(s) that need to be queried. Notice that each of the 5 parameter sets support a kind of Object By Name (OBN), that means you can pass the name or the object itself.</p>
<p><strong>Line 88-89</strong>: The script will use these MoRef collections later on to determine if a specific VM needs to be included in the calculations for the Storage Views values.</p>
<p><strong>Line 92-95</strong>: To determine the Multipathing Status the script first creates a hash table for all the FC HBAs in the ESX(i) servers. The key for this hash table is the WWN, in hex format, for the HBA.</p>
<p><strong>Line 98-171</strong>: The main loop over all the datastores that the script needs to handle.</p>
<p><strong>Line 101-102</strong>: The script collects all the LUNs that are part of the datastore.</p>
<p><strong>Line 103</strong>: The Multipathing logic works with a copy of the hash table that was created earlier.</p>
<p><strong>Line 106-108</strong>: In the hash table the script increments the value for each LUN path that is Active or Standby.</p>
<p><strong>Line 109-114</strong>: If a LUN has more then 1 path, the <strong>Multipathing Status</strong> is considered as <strong>Full Redundancy</strong>. Otherwise the status is <strong>Partial/No Redundancy</strong>.</p>
<p><strong>Line 118-153</strong>: The script calculates all values that are related to the storage in use by the VMs.</p>
<p><strong>Line 125</strong>: For a VM to be taken into account, the VM must use storage on the datastore and must be hosted by one of the ESX(i) host.</p>
<p><strong>Line 127</strong>: This Regular Expression will be used later on to verify the a specific file is located on the datastore. Note that the square brackets need to be escaped.</p>
<p><strong>Line 128</strong>: The Space Used value is the sum of all the Committed space for each of the VMs on that datastore.</p>
<p><strong>Line 129-135</strong>: The space used by snapshots is the sum of all the VMDK snapshot files and the snapshotList and the snapshotData files.</p>
<p><strong>Line 132</strong>: Note that we check for each file used for the Snapshot Space calculation, if it is located on the datastore with the -match operator. This is required since the administrator or user can define that snapshot files need to be stored on another datastore.</p>
<p><strong>Line 136-139</strong>: All the files used for the vDisks of a VM.</p>
<p><strong>Line 140-143</strong>: All swap related files</p>
<p><strong>Line 144-147</strong>: All other files that are used by the VM.</p>
<p><strong>Line 148-151</strong>: This block calculates the Shared Space for a VM. Examples of shared space usage are linked clones that are created from a snapshot with the createNewChildDiskBacking option for the diskMoveType (see the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html" target="_blank" rel="noopener noreferrer">VirtualMachineRelocateSpec</a>).</p>
<p><strong>Line 156-170</strong>: Create the object, per datastore, with all the values. To have similar values that are presented in the Storage Views panel, the script uses the <strong>Get-FriendlyUnits</strong> function from my <a href="https://www.lucd.info/2011/11/06/friendly-units/" target="_blank" rel="noopener noreferrer">Friendly Units</a> post.</p>
<p><strong>Line 166</strong>: Note that for the Virtual Disk Space value we need to subtract the Snapshot Space from the total disk space.</p>
<h2>Samples</h2>
<p>You can pass the function the name of the object for which you want the Storage Views &#8211; Datastore values.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-StorageViewDatastore -Cluster MyCluster |
Select-Object Datastore,&quot;File System Type&quot;,&quot;Connectivity Status&quot;,&quot;Multipathing Status&quot;,
  @{N=&quot;Capacity&quot;;E={&quot;{0,7:f2} {1,2}&quot; -f $_.Capacity.Value,$_.Capacity.Unit}},
  @{N=&quot;Free Space&quot;;E={&quot;{0,7:f2} {1,2}&quot; -f $_.Free.Value,$_.Free.Unit}},
  @{N=&quot;Space Used&quot;;E={if($_.Used.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Used.Value,$_.Used.Unit}}},
  @{N=&quot;Snapshot Space&quot;;E={if($_.Snapshot.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Snapshot.Value,$_.Snapshot.Unit}}},
  @{N=&quot;Virtual Disk Space&quot;;E={if($_.vDisk.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.vDisk.Value,$_.vDisk.Unit}}},
  @{N=&quot;Swap Space&quot;;E={if($_.Swap.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Swap.Value,$_.Swap.Unit}}},
  @{N=&quot;Other VM Space&quot;;E={if($_.Other.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Other.Value,$_.Other.Unit}}},
  @{N=&quot;Shared Space&quot;;E={if($_.Shared.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Shared.Value,$_.Shared.Unit}}} |
Format-Table -AutoSize</pre><p></p>
<p>Or you can pass the actual object.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$dc = Get-Datacenter -Name MyDC
Get-StorageViewDatastore -Datacenter $dc |
Select-Object Datastore,&quot;File System Type&quot;,&quot;Connectivity Status&quot;,&quot;Multipathing Status&quot;,
  @{N=&quot;Capacity&quot;;E={&quot;{0,7:f2} {1,2}&quot; -f $_.Capacity.Value,$_.Capacity.Unit}},
  @{N=&quot;Free Space&quot;;E={&quot;{0,7:f2} {1,2}&quot; -f $_.Free.Value,$_.Free.Unit}},
  @{N=&quot;Space Used&quot;;E={if($_.Used.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Used.Value,$_.Used.Unit}}},
  @{N=&quot;Snapshot Space&quot;;E={if($_.Snapshot.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Snapshot.Value,$_.Snapshot.Unit}}},
  @{N=&quot;Virtual Disk Space&quot;;E={if($_.vDisk.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.vDisk.Value,$_.vDisk.Unit}}},
  @{N=&quot;Swap Space&quot;;E={if($_.Swap.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Swap.Value,$_.Swap.Unit}}},
  @{N=&quot;Other VM Space&quot;;E={if($_.Other.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Other.Value,$_.Other.Unit}}},
  @{N=&quot;Shared Space&quot;;E={if($_.Shared.Value){&quot;{0,7:f2} {1,2}&quot; -f $_.Shared.Value,$_.Shared.Unit}}} |
Export-Csv &quot;C:\SV-MyDC.csv&quot; -NoTypeInformation -UseCulture</pre><p></p>
<p>The previous example also showed how the results can be saved to a CSV file.<br />
Such a CSV file looks as follows.</p>
<p><a href="https://lucd.info/wp-content/uploads/2011/11/SV-DS1.png"><img decoding="async" class="alignnone size-full wp-image-3663" title="SV-DS1" src="https://lucd.info/wp-content/uploads/2011/11/SV-DS1.png" alt="" width="925" height="174" srcset="https://www.lucd.info/wp-content/uploads/2011/11/SV-DS1.png 1321w, https://www.lucd.info/wp-content/uploads/2011/11/SV-DS1-300x56.png 300w, https://www.lucd.info/wp-content/uploads/2011/11/SV-DS1-1024x193.png 1024w" sizes="(max-width: 925px) 100vw, 925px" /></a></p>
<p>Enjoy the function !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2011/11/14/storage-views-datastores/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>Orphaned files and folders &#8211; Spring cleaning</title>
		<link>https://www.lucd.info/2011/04/25/orphaned-files-and-folders-spring-cleaning/</link>
					<comments>https://www.lucd.info/2011/04/25/orphaned-files-and-folders-spring-cleaning/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Mon, 25 Apr 2011 18:53:41 +0000</pubDate>
				<category><![CDATA[datastore]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Virtual Machine]]></category>
		<category><![CDATA[VMDK]]></category>
		<category><![CDATA[disk]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[Folder]]></category>
		<category><![CDATA[PowerCLI]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=3217</guid>

					<description><![CDATA[In our PowerCLI book we presented a Delete-Harddisk function in Chapter 7. One [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In our PowerCLI book we presented a <strong>Delete-Harddisk</strong> function in Chapter 7.</p>
<p>One of our readers asked if that function could be used to remove orphaned VMDK files from one or more datastores. Now unfortunately that is not the case since the function we presented in chapter 7 uses the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html#reconfigure" target="_blank" rel="noopener noreferrer">ReconfigVM_Task</a> method to remove the harddisk.</p>
<p>In the <a href="https://communities.vmware.com/community/vmtn/vsphere/automationtools/powercli?view=discussions" target="_blank" rel="noopener noreferrer">PowerCLI Community</a> there are some thread that provide scripts to report on orphaned VMDK files, but most of these are quite old.</p>
<p>So I decided to write a new script that would report on orphaned folders and VMDK files and that would have an option to remove these folders and files.</p>
<p><span id="more-3217"></span></p>
<h3><span style="background-color: #ffff00;">Update March 19th 2013</span></h3>
<p>The following changes were made to the function</p>
<ul>
<li>Fixed the problem where a VMDK in the root of a datastore, which you shouldn&#8217;t have of course, would erase the complete datastore content (ouch). Thanks Olivier</li>
<li>Added <strong>WhatIf</strong> functionality. You can now check what the <strong>Delete</strong> switch will do before actually removing files and folders.</li>
<li>Added details for lone VMDK. See the properties of the returned objects.</li>
</ul>
<h3><span style="background-color: #ffff00;">Update May 22nd 2011</span></h3>
<p>Two corrections in this new version of the script.</p>
<ul>
<li><a id="commentauthor-987" href="https://www.hypervisor.fr/" rel="external nofollow">NiTRo</a> reported a problem with guests that had only a .vmdk, and not their .vmx, file located on the datastore(s) to be cleaned</li>
<li>The COS became a virtual machine with ESX 4.x and thus has a .vmdk file as well. Although the COS files should be located on a local datastore, the script now ignores COS .vmdk files when it encounters them on the datastore(s) to be cleaned.</li>
</ul>
<h2>The Script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">function Remove-OrphanedData {
&lt;#
.SYNOPSIS   Remove orphaned folders and VMDK files
.DESCRIPTION   The function searches orphaned folders and VMDK files
   on one or more datastores and reports its findings.
   Optionally the function removes  the orphaned folders   and VMDK files
.NOTES   Author:  Luc Dekens
.PARAMETER Datastore
   One or more datastores.
   The default is to investigate all shared VMFS datastores
.PARAMETER Delete
   A switch that indicates if you want to remove the folders
   and VMDK files
.EXAMPLE
   PS&gt; Remove-OrphanedData -Datastore ds1
.EXAMPLE
  PS&gt; Get-Datastore ds* | Remove-OrphanedData
.EXAMPLE
  PS&gt; Remove-OrphanedData -Datastore $ds -Delete
#&gt;

  [CmdletBinding(SupportsShouldProcess=$true)]

  param(
  [parameter(Mandatory=$true,ValueFromPipeline=$true)]
  [PSObject[]]$Datastore,
  [switch]$Delete
  )

  begin{
    $fldList = @{}
    $hdList = @{}

    $fileMgr = Get-View FileManager
  }

  process{
    foreach($ds in $Datastore){
      if($ds.GetType().Name -eq &quot;String&quot;){
        $ds = Get-Datastore -Name $ds
      }
      if($ds.Type -eq &quot;VMFS&quot; -and $ds.ExtensionData.Summary.MultipleHostAccess){
        Get-VM -Datastore $ds | %{
          $_.Extensiondata.LayoutEx.File | where{&quot;diskDescriptor&quot;,&quot;diskExtent&quot; -contains $_.Type} | %{
            $fldList[$_.Name.Split('/')[0]] = $_.Name
            $hdList[$_.Name] = $_.Name
          }
        }
        Get-Template | where {$_.DatastoreIdList -contains $ds.Id} | %{
          $_.Extensiondata.LayoutEx.File | where{&quot;diskDescriptor&quot;,&quot;diskExtent&quot; -contains $_.Type} | %{
            $fldList[$_.Name.Split('/')[0]] = $_.Name
            $hdList[$_.Name] = $_.Name
          }
        }

        $dc = $ds.Datacenter.Extensiondata

        $flags = New-Object VMware.Vim.FileQueryFlags
        $flags.FileSize = $true
        $flags.FileType = $true

        $disk = New-Object VMware.Vim.VmDiskFileQuery
        $disk.details = New-Object VMware.Vim.VmDiskFileQueryFlags
        $disk.details.capacityKb = $true
        $disk.details.diskExtents = $true
        $disk.details.diskType = $true
        $disk.details.thin = $true

        $searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
        $searchSpec.details = $flags
        $searchSpec.Query += $disk
        $searchSpec.sortFoldersFirst = $true

        $dsBrowser = Get-View $ds.ExtensionData.browser
        $rootPath = &quot;[&quot; + $ds.Name + &quot;]&quot;
        $searchResult = $dsBrowser.SearchDatastoreSubFolders($rootPath, $searchSpec)
        foreach($folder in $searchResult){
          if($fldList.ContainsKey($folder.FolderPath.TrimEnd('/'))){
            foreach ($file in $folder.File){
              if(!$hdList.ContainsKey($folder.FolderPath + $file.Path)){
                New-Object PSObject -Property @{
                  Folder = $folder.FolderPath
                  Name = $file.Path
                  Size = $file.FileSize
                  CapacityKB = $file.CapacityKb
                  Thin = $file.Thin
                  Extents = [string]::Join(',',($file.DiskExtents))
                }
                if($Delete){
                  If ($PSCmdlet.ShouldProcess(($folder.FolderPath + &quot; &quot; + $file.Path),&quot;Remove VMDK&quot;)){
                    $dsBrowser.DeleteFile($folder.FolderPath + $file.Path)
                  }
                }
              }
            }
          }
          elseif($folder.File | where {&quot;cos.vmdk&quot;,&quot;esxconsole.vmdk&quot; -notcontains $_.Path}){
            $folder.File | %{
              New-Object PSObject -Property @{
                Folder = $folder.FolderPath
                Name = $_.Path
                Size = $_.FileSize
                CapacityKB = $_.CapacityKB
                Thin = $_.Thin
                Extents = [String]::Join(',',($_.DiskExtents))
              }
            }
            if($Delete){
              if($folder.FolderPath -eq $rootPath){
                $folder.File | %{
                  If ($PSCmdlet.ShouldProcess(($folder.FolderPath + &quot; &quot; + $_.Path),&quot;Remove VMDK&quot;)){
                    $dsBrowser.DeleteFile($folder.FolderPath + $_.Path)
                  }
                }
              }
              else{
                If ($PSCmdlet.ShouldProcess($folder.FolderPath,&quot;Remove Folder&quot;)){
                  $fileMgr.DeleteDatastoreFile($folder.FolderPath,$dc.MoRef)
                }
              }
            }
          }
        }
      }
    }
  }
}</pre><p></p>
<h4>Annotations</h4>
<p><strong>Line 22, 91, 110, 116</strong>: These handle the <strong>WhatIf</strong> switch</p>
<p><strong>Line 26</strong>: The function accepts datastore by name or as a DatastoreImpl object. Hence the PSObject type. There has to be a Datastore argument !</p>
<p><strong>Line 39-41</strong>: Cheap OBN implementation.</p>
<p><strong>Line 42</strong>: The test makes sure only <strong>VMFS</strong> datastores that are <strong>shared</strong> are handled.</p>
<p><strong>Line 43-48</strong>: The function creates a hash table with all the files that are used by the virtual machines on the datastore. The <strong>$fldList</strong> hash table contains the folders and the <strong>$hdList</strong> hash table contains all the disk related files (they have the <strong>diskDescriptor</strong> or the <strong>diskExtent type</strong>).</p>
<p><strong>Line 49-54</strong>: The <a href="https://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-Template.html" target="_blank" rel="noopener noreferrer">Get-Template</a> cmdlet doesn&#8217;t have a <strong>Datastore</strong> parameter, that&#8217;s why this block uses a different method of determining if there are Templates on a specific datastore.</p>
<p><strong>Line 58-75</strong>: The parameters for the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.host.DatastoreBrowser.html#searchSubFolders" target="_blank" rel="noopener noreferrer">SearchDatastoreSubFolders</a> method are prepared and at the end the method is called.</p>
<p><strong>Line 77-105</strong>: The returned results from the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.host.DatastoreBrowser.html#searchSubFolders" target="_blank" rel="noopener noreferrer">SearchDatastoreSubFolders</a> method are analysed.</p>
<p><strong>Line 87,103</strong>: The Extents property will contain all related filenames of the VMDK file. For example, a file called MyVM.vmdk will have an extent called MyVM-flat.vmdk.</p>
<p><strong>Line 89-93</strong>: If the Delete switch is used, the script tests if the WhatIf switch was also specified. If not, the VMDK file is deleted.</p>
<p><strong>Line 109</strong>: This condition handles the case when there is an orphaned VMDK file in the root of the datastore.</p>
<p><strong>Line 110</strong>: For an orphaned VMDK in the root of the datastore, the DeleteFile method is used.</p>
<p><strong>Line 118</strong>: For a folder with orphaned VMDK files, the DeleteDatastoreFile method is used</p>
<h2>Sample runs</h2>
<p>The function will only scan shared VMFS datastores for orphaned folders and files.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Remove-OrphanedData -Datastore DS1</pre><p></p>
<p>This call will display all found folders and files and will not delete them.</p>
<p><a href="https://www.lucd.info/2011/04/25/orphaned-files-and-folders-spring-cleaning/demo2/" rel="attachment wp-att-4386"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-4386" alt="demo2" src="https://lucd.info/wp-content/uploads/2011/04/demo2.png" width="519" height="257" srcset="https://www.lucd.info/wp-content/uploads/2011/04/demo2.png 519w, https://www.lucd.info/wp-content/uploads/2011/04/demo2-300x148.png 300w" sizes="auto, (max-width: 519px) 100vw, 519px" /></a></p>
<p>When you add the <strong>Delete</strong> switch, the function will return the same information, but the folders and files will be deleted.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Remove-OrphanedData -Datastore DS1 -Delete</pre><p></p>
<p>When you combine the <strong>Delete</strong> switch with the <strong>WhatIf</strong> switch, not files or folders will be deleted. But the function will show what actions will be taken without</p>
<p><a href="https://www.lucd.info/2011/04/25/orphaned-files-and-folders-spring-cleaning/demo1-2/" rel="attachment wp-att-4385"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-4385" alt="demo1" src="https://lucd.info/wp-content/uploads/2011/04/demo1.png" width="646" height="145" srcset="https://www.lucd.info/wp-content/uploads/2011/04/demo1.png 646w, https://www.lucd.info/wp-content/uploads/2011/04/demo1-300x67.png 300w" sizes="auto, (max-width: 646px) 100vw, 646px" /></a></p>
<p>You can specify more than one value with the Datastore parameter, the function will investigate all the datastores you specified.<br />
You can pass the datastores by name</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Remove-OrphanedData -Datastore &quot;ds1&quot;,&quot;ds2&quot;</pre><p></p>
<p>or by object</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$ds = Get-Datastore &quot;ds1&quot;
Remove-OrphanedData -Datastore $ds</pre><p></p>
<p>And the function can of course also be used in a pipeline construction</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">Get-Datastore ds* | Remove-OrphanedData -Delete</pre><p></p>
<p><span style="background-color: #ffff00;">Make absolutely sure that you know what you are doing before using the <strong>Delete</strong> switch.</span></p>
<p><span style="background-color: #ffff00;">Use the <strong>WhatIf</strong> switch before actually deleting anything !</span></p>
<p>Enjoy !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2011/04/25/orphaned-files-and-folders-spring-cleaning/feed/</wfw:commentRss>
			<slash:comments>133</slash:comments>
		
		
			</item>
		<item>
		<title>RDM &#038; vMotion: inaccessible direct-access LUN</title>
		<link>https://www.lucd.info/2009/12/16/drm-vmotion-inaccessible-direct-access-lun/</link>
					<comments>https://www.lucd.info/2009/12/16/drm-vmotion-inaccessible-direct-access-lun/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Wed, 16 Dec 2009 21:22:28 +0000</pubDate>
				<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[RDM]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[VMDK]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=1187</guid>

					<description><![CDATA[When you try to migrate a guest, that is using one or more [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>When you try to migrate a guest, that is using one or more <a href="https://pubs.vmware.com/vsp40_e/server_config/wwhelp/wwhimpl/common/html/wwhelp.htm#href=c_about_raw_device_mapping.html&amp;single=true" target="_blank">RDM</a> disks, you might see this message.</p>
<p style="text-align: center;"><a rel="attachment wp-att-1188" href="https://lucd.info/?attachment_id=1188"><img loading="lazy" decoding="async" class="size-full wp-image-1188  aligncenter" title="compatibility" src="https://lucd.info/wp-content/uploads/2009/12/compatibility.png" alt="compatibility" width="535" height="106" srcset="https://www.lucd.info/wp-content/uploads/2009/12/compatibility.png 535w, https://www.lucd.info/wp-content/uploads/2009/12/compatibility-300x59.png 300w" sizes="auto, (max-width: 535px) 100vw, 535px" /><br />
</a></p>
<p>The reason this is most probably because the <strong>LUN IDs</strong> are <strong>different</strong> on the source and the destination ESX server.</p>
<p>One solution is:</p>
<ul>
<li>stop the guest</li>
<li>write down the Physical LUN ID</li>
<li>remove the RDM disk(s)</li>
<li>vMotion the guest</li>
<li>add the RDM disk(s) to the guest based on the Physical LUN ID</li>
<li>start the guest</li>
</ul>
<p>But why do this the hard (manual) way when we have <a href="https://communities.vmware.com/community/vmtn/vsphere/automationtools/windows_toolkit?view=overview" target="_blank">PowerCLI</a> ?</p>
<p><span id="more-1187"></span>Automating the above scenario doesn&#8217;t look too difficult, but there are some pitfalls on the way.</p>
<h2>Gathering the information</h2>
<p>In this step I collect extensive information about the guest and the RDM disk(s) it has connected.</p>
<p>As a safety-measure, the collected information is <strong>dumped</strong> to a <strong>CSV</strong> file. This should allow, in case of script-failure, to restore the RDM mappings quite easily.</p>
<p>The collected information should also include to which <strong>controller</strong> the RDM disk is connected and the RDM&#8217;s <strong>unit number</strong>. This is important because otherwise the guest&#8217;s OS might mix up the drive lettering.</p>
<h2>Removing the RDM</h2>
<p>For this step I use a filter, called <strong>Remove-HD</strong>. This makes it easy to combine this in a pipe with the <strong>Get-Harddisk</strong> cmdlet.</p>
<p>I could have used PowerCLI&#8217;s <strong>Remove-Harddisk</strong> but this cmdlet leaves the mapping files on the datastore and thus makes your guest consume unused disk space.</p>
<p>The filter has two steps, the first one removes the RDM from the guest&#8217;s configuration (<a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualMachine.html#reconfigure" target="_blank">ReconfigVM_Task</a>) and the second step removes (<a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.FileManager.html#deleteFile" target="_blank">DeleteDatastoreFile_Task</a>) the mapping file(s) from the datastore.</p>
<h2>Connecting the RDM</h2>
<p>This function (<strong>New-RawHardDisk</strong>) already appeared in the PowerCLI Community thread <a href="https://communities.vmware.com/message/931649#931649 " target="_blank">Adding an existing hard disk</a>. I just added some logic to be able to add physical and virtual mode RDMs.</p>
<h2>Main function</h2>
<p>This is driving part of the script. It controls the logic and the order in which the different functions and filters are called.</p>
<h2>The script</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># ESX server against which you want to execute the script
$tgtESX = &quot;My-target-ESX-host&quot;

# Attach a RDM disk to a VM on a specified controller
function New-RawHardDisk{
	param($vm, $DeviceName, $DiskType, $controller, $unitnumber, $capacity)

	$vmMo = $vm | Get-View
	$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
	$chg = New-Object VMware.Vim.VirtualDeviceConfigSpec
	$chg.operation = &quot;add&quot;
	$chg.fileoperation = &quot;create&quot;
	$dev = New-Object VMware.Vim.VirtualDisk
	$dev.CapacityInKB = $capacity
	$dev.Key = - 100
	$back = New-Object VMware.Vim.VirtualDiskRawDiskMappingVer1BackingInfo
	$back.deviceName = $devicename
	if($DiskType -eq &quot;RawPhysical&quot;){
		$back.compatibilityMode = &quot;physicalMode&quot;
	}
	else{
		$back.compatibilityMode = &quot;virtualMode&quot;
	}
	$back.FileName = &quot;&quot;
	$dev.Backing = $back
	$dev.ControllerKey = $controller
	$dev.UnitNumber = $unitnumber
	$chg.device = $dev
	$spec.deviceChange += $chg
	$taskMoRef = $vmMo.ReconfigVM_Task($spec)
	$task = Get-View $taskMoRef
	while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
		$task.UpdateViewData(&quot;Info.State&quot;)
	}
	$task.UpdateViewData(&quot;Info.Result&quot;)
}

# Remove a RDM disk from a VM and optionally delete the backing file
filter remove-HD {
	param($Delete)
	$HDname = $_.Name
	$vm = Get-View -Id $_.ParentId
	# Get device key for the hard disk
	foreach($dev in $vm.Config.Hardware.Device){
		if ($dev.DeviceInfo.Label -eq $HDname){
			continue
		}
	}
	$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
	$spec.deviceChange = @()
	$spec.deviceChange += New-Object VMware.Vim.VirtualDeviceConfigSpec
	$spec.deviceChange[0].device = New-Object VMware.Vim.VirtualDevice
	$spec.deviceChange[0].device.key = $dev.Key
	$spec.deviceChange[0].device.unitnumber = $dev.UnitNumber
	$spec.deviceChange[0].operation = &quot;remove&quot;
	$taskMoRef = $vm.ReconfigVM_Task($spec)
	$task = Get-View $taskMoRef
	while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
		$task.UpdateViewData(&quot;Info.State&quot;)
	}
	$task.UpdateViewData(&quot;Info.Result&quot;)

# Remove hard disk files (backing) from datastore
	if ($Delete){
		$fileMgr = Get-View (Get-View ServiceInstance).Content.fileManager
		$datacenter = (Get-View (Get-VM $vm.name | Get-Datacenter).ID).get_MoRef()
		foreach($disk in $vm.LayoutEx.Disk){
			if($disk.Key -eq $dev.Key){
				foreach($chain in $disk.Chain){
					foreach($fileKey in $chain.FileKey){
						$name = $vm.LayoutEx.File[$fileKey].Name
						$taskMoRef = $fileMgr.DeleteDatastoreFile_Task($name, $datacenter)
						$task = Get-View $taskMoRef
						while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
							$task.UpdateViewData(&quot;Info.State&quot;)
						}
						$task.UpdateViewData(&quot;Info.Result&quot;)
					}
				}
				continue
			}
		}
	}
}

# Main
$report = @()

# Report on all the VMs that have a RDM
$vms = Get-View -ViewType VirtualMachine
foreach($vm in $vms){
	foreach($dev in $vm.Config.Hardware.Device){
		if(($dev.gettype()).Name -eq &quot;VirtualDisk&quot;){
			if(($dev.Backing.CompatibilityMode -eq &quot;physicalMode&quot;) -or
			($dev.Backing.CompatibilityMode -eq &quot;virtualMode&quot;)){
				$esx = Get-View $vm.Runtime.Host
				$lun = $esx.Config.StorageDevice.ScsiLun | where {$_.Uuid -eq $dev.Backing.LunUuid}
				$report += New-Object PSObject -Property @{
					VMName = $vm.Name
					VMHost = ($esx).Name
					HDLabel = $dev.DeviceInfo.Label
					HDDeviceName = $dev.Backing.DeviceName
					HDFileName = $dev.Backing.FileName
					HDMode = $dev.Backing.CompatibilityMode
					HDSize = $dev.CapacityInKB
					LunDisplayName = $lun.DisplayName
					HDCtrlType = ($vm.Config.Hardware.Device | where {$_.Key -eq $dev.ControllerKey}).GetType().Name
					HDController = $dev.ControllerKey
					HDUnit = $dev.UnitNumber
					HDDiskMode = $dev.Backing.DiskMode
					LunCanonical = $lun.CanonicalName
					LunDeviceName = $lun.DeviceName
				}
			}
		}
	}
}
$report | Export-Csv &quot;C:\VM-with-RDM.csv&quot; -NoTypeInformation -UseCulture

$report | Group-Object -Property VMName | % {
	$vm = Get-VM $_.Name
# Stop the VM
	Write-Host &quot;Stop VM&quot; $_.Name
	$VM | Get-VMGuest | where {$_.State -eq &quot;Running&quot;} | Shutdown-VMGuest - Confirm:$false
# Remove the RDM disk(s)
	$_.Group | % {
		Write-Host &quot;`tremove HD&quot; $_.HDLabel
		$vm | Get-HardDisk -DiskType (&quot;Raw&quot; + $_.HDMode.TrimEnd(&quot;Mode&quot;)) | Remove-HD - Delete:$true
	}
# vMotion the VM
	Write-Host &quot;Moving VM&quot;
	$newvm = $vm | Move-VM -Destination (Get-VMHost -Name $tgtESX)
# Attach the RDM disk(s) back
	$_.Group | % {
		Write-Host &quot;`tAdd HD&quot; $_.HDLabel
		New-RawHardDisk -Vm $newvm -DiskType (&quot;Raw&quot; + $_.HDMode.TrimEnd(&quot;Mode&quot;)) -DeviceName $_.LunDeviceName -Controller $_.HDController -UnitNumber $_.HDUnit -Capacity $_.HDSize
	}
# Power on the VM
	Write-Host &quot;Start VM&quot; $_.Name
	$newvm | Start-VM - Confirm:$false
}</pre><p></p>
<h2>Annotation</h2>
<p><strong>Line 2</strong>: destination ESX server</p>
<p><strong>Line 18-23</strong>: support for physical and virtual mode RDM</p>
<p><strong>Line 118</strong>: dump the RDM info to a CSV file</p>
<p><strong>Line 120-141</strong>: this is the part where the RDM disk(s) are removed, the VM vMotioned and the RDM disk(s) re-attached.<strong><br />
</strong></p>
<p><strong>Line 136</strong>: because a guest can have more than one RDM I use the Group-Object cmdlet</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2009/12/16/drm-vmotion-inaccessible-direct-access-lun/feed/</wfw:commentRss>
			<slash:comments>20</slash:comments>
		
		
			</item>
		<item>
		<title>Scripts for Yellow Bricks&#8217; advise: Thin Provisioning alarm &#038; eagerZeroedThick</title>
		<link>https://www.lucd.info/2009/11/15/scripts-for-yellow-bricks-advise-thin-provisioning-alarm-eagerzeroedthick/</link>
					<comments>https://www.lucd.info/2009/11/15/scripts-for-yellow-bricks-advise-thin-provisioning-alarm-eagerzeroedthick/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 15 Nov 2009 18:56:22 +0000</pubDate>
				<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Thin Provisioning]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[VMDK]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=918</guid>

					<description><![CDATA[On the Yellow Bricks blog there was today a very interesting entry called [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>On the <a href="https://www.yellow-bricks.com/" target="_blank" rel="noopener noreferrer">Yellow Bricks</a> blog there was today a very interesting entry called <a href="http://www.yellow-bricks.com/2009/11/15/performance-thin-provisioning/" target="_blank" rel="noopener noreferrer">Performance : Thin Provisioning</a>. Besides the link to the excellent VMware document called <a href="https://www.vmware.com/pdf/vsp_4_thinprov_perf.pdf" target="_blank" rel="noopener noreferrer">Performance Study of VMware vStorage Thin Provisioning</a>, Duncan also included some tips and tricks.</p>
<p>Since I&#8217;m in favour of automating as much as possible in my vSphere environment, I decided to have a look how all this could be scripted.</p>
<h2><span id="more-918"></span>Alarm</h2>
<p>The following script will create an alarm that will be <strong>triggered</strong> by the status of two metrics directly related to Thin Provisioning:</p>
<ul>
<li>Disk Overallocation</li>
<li>Disk Usage</li>
</ul>
<p><a rel="attachment wp-att-919" href="https://www.lucd.info/2009/11/15/scripts-for-yellow-bricks-advise-thin-provisioning-alarm-eagerzeroedthick/thin-alarm-triggers/"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-919" title="Thin-Alarm-triggers" src="https://lucd.info/wp-content/uploads/2009/11/Thin-Alarm-triggers.png" alt="Thin-Alarm-triggers" width="575" height="106" srcset="https://www.lucd.info/wp-content/uploads/2009/11/Thin-Alarm-triggers.png 719w, https://www.lucd.info/wp-content/uploads/2009/11/Thin-Alarm-triggers-300x55.png 300w" sizes="auto, (max-width: 575px) 100vw, 575px" /></a></p>
<p>The script will define two <strong>actions</strong> on the alarm:</p>
<ul>
<li>Send an email</li>
<li>Send a SNMP trap</li>
</ul>
<p><a rel="attachment wp-att-920" href="https://www.lucd.info/2009/11/15/scripts-for-yellow-bricks-advise-thin-provisioning-alarm-eagerzeroedthick/thin-alarm-actions/"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-920" title="Thin-Alarm-actions" src="https://lucd.info/wp-content/uploads/2009/11/Thin-Alarm-actions.png" alt="Thin-Alarm-actions" width="582" height="145" srcset="https://www.lucd.info/wp-content/uploads/2009/11/Thin-Alarm-actions.png 728w, https://www.lucd.info/wp-content/uploads/2009/11/Thin-Alarm-actions-300x74.png 300w" sizes="auto, (max-width: 582px) 100vw, 582px" /></a></p>
<p>You can of course adapt the triggers and the alarms.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$datacenterName =
$mailTo = &quot;luc.dekens@lucd.info&quot;

$alarmMgr = Get-View AlarmManager
$entity = Get-Datacenter $datacenterName | Get-View

# AlarmSpec
$alarm = New-Object VMware.Vim.AlarmSpec
$alarm.Name = &quot;Thin Provisioning&quot;
$alarm.Description = &quot;Thin Provisioning alarm by LucD&quot;
$alarm.Enabled = $TRUE

# Action 1 - Send email
$alarm.action = New-Object VMware.Vim.GroupAlarmAction

$trigger1 = New-Object VMware.Vim.AlarmTriggeringAction
$trigger1.action = New-Object VMware.Vim.SendEmailAction
$trigger1.action.ToList = $mailTo
$trigger1.action.Subject = &quot;Thin Provisioning Alarm&quot;
$trigger1.Action.CcList = &quot;&quot;
$trigger1.Action.Body = &quot;&quot;

# Transition 1a - yellow --&gt; red
$trans1a = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans1a.StartState = &quot;yellow&quot;
$trans1a.FinalState = &quot;red&quot;

# Transition 1b - red --&gt; yellow
$trans1b = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans1b.StartState = &quot;red&quot;
$trans1b.FinalState = &quot;yellow&quot;

$trigger1.TransitionSpecs += $trans1a
$trigger1.TransitionSpecs += $trans1b

# Action 2 - Send SNMP trap

$trigger2 = New-Object VMware.Vim.AlarmTriggeringAction
$trigger2.action = New-Object VMware.Vim.SendSNMPAction

# Transition 2a - yellow --&gt; red
$trans2a = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans2a.StartState = &quot;yellow&quot;
$trans2a.FinalState = &quot;red&quot;

# Transition 2b - yellow --&gt; red
$trans2b = New-Object VMware.Vim.AlarmTriggeringActionTransitionSpec
$trans2b.StartState = &quot;red&quot;
$trans2b.FinalState = &quot;yellow&quot;

$trigger2.TransitionSpecs += $trans2a
$trigger2.TransitionSpecs += $trans2b

$alarm.action.action += $trigger1
$alarm.action.action += $trigger2

# Expression 1 - Overallocation
$expression1 = New-Object VMware.Vim.MetricAlarmExpression
$expression1.Metric = New-Object VMware.Vim.PerfMetricId
$expression1.Metric.CounterId = 196
$expression1.Metric.Instance = &quot;&quot;
$expression1.Operator = &quot; isAbove&quot;
$expression1.Red = 30000
$expression1.Yellow = 10000
$expression1.Type = &quot;Datastore&quot;

# Expression 2 - Disk usage
$expression2 = New-Object VMware.Vim.MetricAlarmExpression
$expression2.Metric = New-Object VMware.Vim.PerfMetricId
$expression2.Metric.CounterId = 165
$expression2.Metric.Instance = &quot;&quot;
$expression2.Operator = &quot; isAbove&quot;
$expression2.Red = 9000
$expression2.Yellow = 7500
$expression2.Type = &quot;Datastore&quot;

$alarm.expression = New-Object VMware.Vim.OrAlarmExpression
$alarm.expression.expression += $expression1
$alarm.expression.expression += $expression2

$alarm.setting = New-Object VMware.Vim.AlarmSetting
$alarm.setting.reportingFrequency = 0
$alarm.setting.toleranceRange = 0

# Create alarm.
$alarmMgr.CreateAlarm($entity.MoRef, $alarm)</pre><p></p>
<p>Annotations</p>
<p>Line 5: the script defines the alarm on a Datacenter but you can of course change this to another entity (where the alarm makes sense)</p>
<p>Line 20-21: the SendEmailAction seems to require that the CcList and Body properties are explicitly blanked out</p>
<p>Line 23-31, 41-49: I set up the alarm to trigger the actions when going from <strong>yellow</strong> to <strong>red </strong>but also from <strong>red</strong> to <strong>yellow</strong>. That way you&#8217;re informed when the situation goes back to &#8220;<em>nearly</em>&#8221; normal. You can change this behavior or even add additional transition states.</p>
<p>Line 60, 70: the CounterId properties can be obtained from the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.PerformanceManager.html" target="_blank" rel="noopener noreferrer">PerformanceManager</a>.</p>
<h2>eagerZeroedThick</h2>
<p>This script will convert an existing thick VMDK to <strong>eagerZeroedThick</strong>. As you can read in Duncan&#8217;s blog entry there is a serious performance improvement to be obtained by doing this.</p>
<p>Note that the guest needs to be <strong>powered off</strong> to be able to do the conversion ! This is in fact the case for most of the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualDiskManager.html" target="_blank" rel="noopener noreferrer">VirtualDiskManager</a> methods. See also my <a href="https://lucd.info/?p=859" target="_blank" rel="noopener noreferrer">Thick to Thin with PowerCLI and the SDK</a> entry.</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vmName = &lt;vm-name&gt;
$vCenter = &lt;vCenter-name&gt;
$esxAccount = &lt;ESX-account&gt;
$esxPasswd = &lt;ESX-password&gt;

function Set-EagerZeroThick{
	param($vcName, $vmName, $hdName)

# Find ESX host for VM
	$vcHost = Connect-VIServer -Server $vcName -Credential (Get-Credential -Credential &quot;vCenter account&quot;)
	$vmImpl = Get-VM $vmName
	if($vmImpl.PowerState -ne &quot;PoweredOff&quot;){
		Write-Host &quot;Guest must be powered off to use this script !&quot; -ForegroundColor red
		return $false
	}

	$vm = $vmImpl | Get-View
	$esxName = (Get-View $vm.Runtime.Host).Name
# Find datastore path
	$dev = $vm.Config.Hardware.Device | where {$_.DeviceInfo.Label -eq $hdName}
	if($dev.Backing.thinProvisioned){
		return $false
	}
	$hdPath = $dev.Backing.FileName

# For Virtual Disk Manager we need to connect to the ESX server
	$esxHost = Connect-VIServer -Server $esxName -User $esxAccount -Password $esxPasswd

# Convert HD
	$vDiskMgr = Get-View -Id (Get-View ServiceInstance -Server $esxHost).Content.VirtualDiskManager
	$dc = Get-Datacenter -Server $esxHost | Get-View
	$taskMoRef = $vDiskMgr.EagerZeroVirtualDisk_Task($hdPath, $dc.MoRef)
	$task = Get-View $taskMoRef
	while(&quot;running&quot;,&quot;queued&quot; -contains $task.Info.State){
		$task.UpdateViewData(&quot;Info&quot;)
	}

	Disconnect-VIServer -Server $esxHost -Confirm:$false

# Connect to the vCenter
	Connect-VIServer -Server $vcName -Credential (Get-Credential -Credential &quot;vCenter account&quot;)
	if($task.Info.State -eq &quot;success&quot;){
		return $true
	}
	else{
		return $false
	}
}

Set-EagerZeroThick $vCenter $vmName &quot;Hard disk 1&quot;</pre><p></p>
<p>Annotations</p>
<p>Line 3-4: provide an account and password which can logon to the ESX server and which has root authority</p>
<p>Line 12-14: the guest needs to be <strong>powered off</strong> to use the function</p>
<p>Line 21-23: the function only works for thick VMDKs. This tests for thin VMDKs and returns immediatly</p>
<p>Line 31: since we&#8217;re connected to an ESX server there is only one datacenter with the default name <strong>ha-datacenter</strong></p>
<p>Line 32: the core of the function is the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualDiskManager.html#eagerZeroVirtualDisk" target="_blank" rel="noopener noreferrer">EagerZeroVirtualDisk_Task</a> method</p>
<p>As always, please <strong>test</strong> this <strong>thoroughly</strong> in your <strong>test environment</strong> before you use any of this in your production environment !!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2009/11/15/scripts-for-yellow-bricks-advise-thin-provisioning-alarm-eagerzeroedthick/feed/</wfw:commentRss>
			<slash:comments>37</slash:comments>
		
		
			</item>
		<item>
		<title>Thick to Thin with PowerCLI and the SDK</title>
		<link>https://www.lucd.info/2009/11/08/thick-to-thin-with-powercli-and-the-sdk/</link>
					<comments>https://www.lucd.info/2009/11/08/thick-to-thin-with-powercli-and-the-sdk/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Sun, 08 Nov 2009 22:34:24 +0000</pubDate>
				<category><![CDATA[PowerCLI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Thin Provisioning]]></category>
		<category><![CDATA[vSphere]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[VMDK]]></category>
		<guid isPermaLink="false">http://lucd.info/?p=859</guid>

					<description><![CDATA[One of the interesting new features in vSPhere is vStorage Thin Provisioning. I&#8217;m [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>One of the interesting new features in vSPhere is <a href="https://www.vmware.com/products/vstorage-thin-provisioning/" target="_blank">vStorage Thin Provisioning</a>. I&#8217;m not going to explain what Thin Provisioning is all about. For that you can consult several knowledgeable blogs (for example <a href="https://virtualgeek.typepad.com/virtual_geek/2009/04/thin-on-thin-where-should-you-do-thin-provisioning-vsphere-40-or-array-level.html" target="_blank">this entry</a> on Virtual Geek) and/or books (for example Scott Lowe&#8217;s excellent <a href="https://blog.scottlowe.org/2009/04/21/mastering-vmware-vsphere-40/" target="_blank">Mastering VMware vSphere 4.0</a>).</p>
<p>The problem I have with Thin Provisioning, is that there are a lot of existing guests and templates out there that were created with Thick VMDKs in the past. The only documented way I could find to convert these Thick VMDKs to Thin VMDKs was to use svMotion from the vSphere client.</p>
<p>Now that is not a solution I want to (or can) use in an automated environment.<span id="more-859"></span>I could of course &#8217;emulate&#8217; the svMotion process in a PowerShell script with the RelocateVM method, but that is in my opinion not really an ideal solution.</p>
<p>Luckily there is the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualDiskManager.html" target="_blank">VirtualDiskManager</a> with some handy methods like the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualDiskManager.html#copyVirtualDisk" target="_blank">CopyVirtualDisk_Task</a> method.</p>
<p>This method combined with the <a href="https://www.vmware.com/support/developer/vc-sdk/visdk400pubs/ReferenceGuide/vim.VirtualMachine.html#reconfigure" target="_blank">ReconfigVM_Task</a> method ultimately gave me a working solution. With the following script I succeeded in converting a Thick VMDK into a Thin VMDK <strong>in place</strong>. My &#8220;in place&#8221; statement is of course relative, you have to have enough free space in the datastore to create a Thin version of the VMDK besides the Tick version of the VMDK. Once the reconfiguration is done you can safely remove the Thick VMDK file(s).</p>
<p>The guest has to be <strong>powered off</strong> for the following script to work !</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">$vmName = "guest-name"
$vCenter = "vCenter-hostname"
$esxAccount = "ESX-account"
$esxPasswd = "ESX-password"

$vcHost = Connect-VIServer -Server $vCenter
$vmImpl = Get-VM $vmName
if($vmImpl.PowerState -ne "PoweredOff"){
 Write-Host "Guest must be powered off to use this script !" -ForegroundColor red
 exit
}
$vm = $vmImpl | Get-View
$esxName = (Get-View $vm.Runtime.Host).Name

# For Virtual Disk Manager we need to connect to the ESX server
$esxHost = Connect-VIServer -Server $esxName -User $esxAccount -Password $esxPasswd

$vDiskMgr = Get-View -Id (Get-View ServiceInstance).Content.VirtualDiskManager
$firstHD = $true
$vm.Config.Hardware.Device | where {$_.GetType().Name -eq "VirtualDisk"} | % {
 if(!$_.Backing.ThinProvisioned){
 $dev = $_
 $srcName = $dev.Backing.FileName
 $dstName = $srcName.Replace("/","/thin_")
 $esx = Get-View $vm.Runtime.Host
 $srcDC = Get-Datacenter | Get-View
 $spec = New-Object VMware.Vim.VirtualDiskSpec
 $controller = $vm.Config.Hardware.Device | where {$_.Key -eq $dev.ControllerKey}
 switch($controller.GetType().Name){
 "VirtualBusLogicController" {$adapter = "busLogic"}
 "VirtualIDEController" {$adapter = "ide"}
 "VirtualLsiLogicController" {$adapter = "lsiLogic"}
 "VirtualLsiLogicSASController" {$adapter = "lsiLogic"}
 "ParaVirtualSCSIController" {$adapter = ""}
 "Default"{
 Write-Host "Unknown controller type"
 exit
 }
 }
 $spec.adapterType = $adapter
 $spec.diskType = "thin"

 $taskMoRef = $vDiskMgr.CopyVirtualDisk_Task($srcName, $srcDC.MoRef, $dstName, $srcDC.MoRef, $spec, $false)
 $task = Get-View $taskMoRef
 while("running","queued" -contains $task.Info.State){
 $task.UpdateViewData("Info")
 }

 if($firstHD){
 $specHD = New-Object VMware.Vim.VirtualMachineConfigSpec
 $firstHD = $false
 }
 $deviceMod = New-Object VMware.Vim.VirtualDeviceConfigSpec
 $deviceMod.device = $dev
 $deviceMod.device.Backing.FileName = $dstName
 $deviceMod.Operation = "edit"
 $specHD.deviceChange += $deviceMod
 }
}
Disconnect-VIServer -Server $esxHost -Confirm:$false

# For the reconfiguration of the VM we connect to the vCenter
Connect-VIServer -Server $vCenter
$taskMoRef = $vm.ReconfigVM_Task($specHD)
$task = Get-View $taskMoRef
while("running","queued" -contains $task.Info.State){
 $task.UpdateViewData("Info")
}</pre><p></p>
<p>Annotation:</p>
<p>Line 3-4: provide an ESX account and password with root access on the ESX server</p>
<p>Line 8-11: the guest must be powered off for this script to work</p>
<p>Line 16: the VirtualDiskManager methods can only be used when connected to an ESX</p>
<p>Line 20: this loops through all devices and finds the Thick VMDKs</p>
<p>Line 24: the backing filename of the Thin VMDK is the same as the backing filename of the Thick VMDK with a &#8220;thin_&#8221; prefix</p>
<p>Line 29-39: this Switch construct provides the correct adapter name. Take note that the adapter names are case-sensitive</p>
<p>Line 41: the diskType property allows to specify what VMDK format the copy should have</p>
<p>Line 43: the CopyVirtualDisk_Task method creates a Thin copy of the Thick VMDK</p>
<p>Line 49-59: this construct creates the specification for the ReconfigVM_Task method</p>
<p>Line 64: the new Thin VMDKs are now connected (as backing file(s)) to the VM</p>
<p>Note that the script <strong>doesn&#8217;t remove</strong> the Thick VMDK files from the VM&#8217;s directory. This is a safety precaution should something go wrong with the conversion.</p>
<p>Note that this procedure was tested and tried in my environment and seems to work correctly. If you are going to use this script, first try it out in your test environment and make sure the guests with the Thin VMDKs are working correctly !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2009/11/08/thick-to-thin-with-powercli-and-the-sdk/feed/</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
	</channel>
</rss>
