Archive VMs with PowerCLI

Hey Peeps vNoob here

This happens to me ocassionally so naturally I assume everyone else is plagued by the same issue.

Every once and a while I need to “archive a VM” from one of my environments. Essentially this means that we no longer need the VM but we just don’t want to outright delete. At the same time it is taking up storage space and backup space, so we don’t want to just leave it turned off.

In these instance we choose to copy all of the VM files, vmdks, vmx etc etc to a physical server that has massive storage where all our archived files go to spend the rest of their days.

Most times I just turn off the VM and copy all the files using the vSphere Client GUI, but recently I just wanted to script it out.

I did the script because, A. I wanted to and B. I wanted it to take into account if the VM files are spread across more than one datastore, so I wouldn’t have to hunt any of the files down.

Anyway here is the script.

$vm=”VMName1, VMName2″
$local=”LocalStorage Location”

Disconnect-viserver * -confirm:$false -ErrorAction silentlycontinue

Connect-VIServer -Server “$fromvcenter”
$vmbases=get-vm $vm
ForEach ($vmbase in $vmbases)
$vmdisks=$vmbase |Get-HardDisk
$vmfolder=$vmdisks[0].fileName.Split(” “)[1].split(“/”)[0]
$local=”$local” + “\” +”$vmfolder” +”\”

FOREACH ($vmstore in $vmdatastore)

Remove-PSDrive -Name fromds -ErrorAction silentlycontinue
New-PSDrive -location ($vmstore) -Name fromds -PSProvider VimDatastore -Root “\”
Copy-DatastoreItem -Item fromds:\$vmfolder\* -Destination $local -Force


A couple things about this script. Just replace the 3 variables at the top with what you want and you are good to go. Secondly, because you are potentially copying big files, this could take a long time. Plan accordingly and make sure the place your are running the script from will be online long enough and be sure to run the script from a location which will expedite the files being transferred.


I love that this script will grab all the files from potentially several datastores, however, it will only do this if the VM Folder name is consistent across the datastores.


Also using the Copy-DatastoreItem cmdlet, it automatically gives you a nice progress bar…

So it is nice to know where you stand.

Hope this helps everyone!!!!


IF you don’t want a quick shameless plug stop now! 🙂

Quick Shameless Plug

Atwell and I are doing a VMWorld2013 Session, You should vote for it!

And the Description


One thought on “Archive VMs with PowerCLI”

Comments are closed.