VMware

Register All VMs from a Datastore

Quick post this one, I discovered this script when I was looking to register VMs as part of a temporary DR solution, unfortunately I cannot remember where I found the script and therefore I apologise to the original creator.

The idea behind the script is to search through the datastore or datastores that you select, discover the location of the .vmx files on the datastores and then registering the virtual machines associated with the .vmx files into the virtual environment.

Here’s the script, items in bold and italic should be changed:

connect-viserver vcenterservername

$Cluster = "clustername"
$Datastores = "datastorename"
$VMFolder = "destinationfolderforvms"
$ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1
 
foreach($Datastore in Get-Datastore $Datastores) {
 # Set up Search for .VMX Files in Datastore
 $ds = Get-Datastore -Name $Datastore | %{Get-View $_.Id}
 $SearchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
 $SearchSpec.matchpattern = "*.vmx"
 $dsBrowser = Get-View $ds.browser
 $DatastorePath = "[" + $ds.Summary.Name + "]"
 
 # Find all .VMX file paths in Datastore, filtering out ones with .snapshot (Useful for NetApp NFS)
 $SearchResult = $dsBrowser.SearchDatastoreSubFolders($DatastorePath, $SearchSpec) | where {$_.FolderPath -notmatch ".snapshot"} | %{$_.FolderPath + ($_.File | select Path).Path}
 
 #Register all .vmx Files as VMs on the datastore
 foreach($VMXFile in $SearchResult) {
 New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -RunAsync
 }
}

Leave a Reply

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