Richard Parmiter

Virtualisation blog and Knowledge Base

  • You are here: 
  • Home
  • Add VMs to vCenter from an unknown datastore

Add VMs to vCenter from an unknown datastore

Posted on October 17th, 2012

Sometimes it may be required to add VMs to vCenter from a recovered or new datastore. This can be performed manually by adding a new VM and browsing the datastore to attach the disk from the .vmdk file or adding the .vmx files.

However, for datastores that contain many virtual machines, this is laborious and time consuming and it is beneficial to script this where possible.

A script to do this is as follows:

$Cluster = “vCenter Cluster Name”
$Datastores = “vSphere Datastore Name”
$VMFolder = “VM Folder Name”
$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 $Folder -RunAsync
}
}

It is also a useful script if replicating virtual machines to backup storage for DR purposes. If you ever need to use the backup storage, simply attach it to the vSphere cluster and run the script to quickly add all the VM’s that reside on it.

Ref: I found this script on the following blog: Wood IT Work

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites
  • FriendFeed
  • Google Buzz
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • RSS

Tags: , , , ,
Filed under Scripts/Reg, VMWare |

Leave a Reply

*