Find Orphaned VMDK’s

A script to find orphaned vmdk’s on your ESX infrastructure.

Source here: http://communities.vmware.com/docs/DOC-6960

[wpdm_file id=”13″]

If you want to run it to ESX 3.5 make sure you include the snapshot files extension for it (000001.vmdk and so on).

In the following example 00001 and 00002 are added:

#
# Purpose : List all orphaned vmdk on all datastores in all VC's
# Version: 1.0
# Author  : HJA van Bokhoven

#Main

$arrayVC = "YourVirtualCenter"
$OutputFile = "c:\OrphanedVMDK.txt"

Foreach ($strVC in $arrayVC)
{
	Connect-VIServer $strVC
	$arrUsedDisks = Get-VM | Get-HardDisk | %{$_.filename}
	$arrDS = Get-Datastore
	Foreach ($strDatastore in $arrDS)
	{
	   $strDatastoreName = $strDatastore.name
	   Write-Host $strDatastoreName
	   $ds = Get-Datastore -Name $strDatastoreName | %{Get-View $_.Id}
	   $fileQueryFlags = New-Object VMware.Vim.FileQueryFlags
	   $fileQueryFlags.FileSize = $true
	   $fileQueryFlags.FileType = $true
	   $fileQueryFlags.Modification = $true
	   $searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
	   $searchSpec.details = $fileQueryFlags
	   $searchSpec.sortFoldersFirst = $true
	   $dsBrowser = Get-View $ds.browser
	   $rootPath = "["+$ds.summary.Name+"]"
	   $searchResult = $dsBrowser.SearchDatastoreSubFolders($rootPath, $searchSpec)
	   $myCol = @()
	   foreach ($folder in $searchResult)
	   {
	      foreach ($fileResult in $folder.File)
	      {
             $file = "" | select Name, FullPath
		     $file.Name = $fileResult.Path
		     $strFilename = $file.Name
		     IF ($strFilename)
		     {
		     IF ($strFilename.Contains(".vmdk"))
		     {
		     IF (!$strFilename.Contains("-flat.vmdk"))
		     {
		     IF (!$strFilename.Contains("delta.vmdk"))
		     {
		     IF (!$strFilename.Contains("000001.vmdk"))
		     {
		     IF (!$strFilename.Contains("000002.vmdk"))
		     {
		        $strCheckfile = "*"+$file.Name+"*"
			 IF ($arrUsedDisks -Like $strCheckfile){}
	         ELSE
			 {
			 $strOutput = $strDatastoreName + " Orphaned VMDK Found: " + $strFilename
			 $strOutput | Out-File $Outputfile -width 150 -Append
			 }
		     }
		     }
		     }
		     }
		     }
		     }
	      }
	   }
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *