Skip to content

VM Export/Import PowerCLI Script

I wrote this little script snippet to export and import virtual machines from one vCenter to another. This might help for migrations where you have to add virtual machines from a datastore manually to the vCenter inventory. This script does not export any virtual machine disks or configuration files. It's only supposed as replacement for adding virtual machines from an existing datastore the the inventory.

Export VMs
The script is cluster-based. Use the script multiple times if you have more than one cluster. You have to replace "MyCluster" with your clusters name. The Script will export information about all VMs to the $inventory array, and additionally to a csv file. You can always use the csv file load your inventory back to the $inventory array. The script exports:

  • VM-Name
  • VMX Path
  • Resource Pool
  • VM Folder
$cluster = Get-Cluster MyCluster

$inventory = Get-Cluster $cluster | Get-VM | 
Add-Member -MemberType ScriptProperty -Name 'VMXPath' -Value {$this.extensiondata.config.files.vmpathname} -Passthru -Force | 
Select-Object Name,ResourcePool,Folder,VMXPath

$inventory |Export-Csv inventory.csv

Import VMs
To add virtual machines back to the inventory, connect to the vCenter server where you want to add the VMs. You have to create the cluster and any resource pools or VM-Folders prior to use the script. The structure has to be identical to the vCenter where the VMs have been exported from. You also have to mount the original datastores.

(optional) Load the csv file back to the $inventory array:

$inventory = Import-Csv inventory.csv

Add VMs back to the inventory:

$cluster = Get-Cluster MyCluster

foreach($vm in $inventory){
  $ESXHost = Get-Cluster $cluster | Get-VMHost | select -First 1
  New-VM -VMFilePath $vm.VMXPath -VMHost $ESXHost -Location $vm.Folder -ResourcePool (Get-Cluster $cluster | Get-ResourcePool $vm.ResourcePool)

3 thoughts on “VM Export/Import PowerCLI Script”

  1. Hi, I want to import a list of VMs from a CSV file into PS and move those VMs into a different folder.

    Much like your script above "foreach($vm in $inventory){"

    Your parameter $vm is empty. Can you define that for me? It'll help me with my script

    foreach ($vm in $vms){
    Get-VM $ | Move-VM -VM $vm.foldername

    1. $inventory is imported from a CSV File: $inventory = Import-Csv inventory.csv
      $vm is the variable for each loop

      To move a VM into a folder you have to use: Move-VM -VM VM -Destination Folder

Leave a Reply

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