##
## Create a backup of all the vm's
##
$dest = "D:\backup"
$VM_Service = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemManagementService
$ListofVMs = get-wmiobject -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName <> Name"
foreach ($VM in [array] $ListOfVMs)
{
$VMReturnState = $VM.EnabledState
$VMName = $VM.ElementName
if (($VM.EnabledState -eq 2) -or ($VM.EnabledState -eq 32768) -or ($VM.EnabledState -eq 32770))
{
$VM.RequestStateChange(32769)
echo "Saving the state of $VMName"
}
while (!($VM.EnabledState -eq 32769) -and !($VM.EnabledState -eq 3))
{
Start-Sleep(1)
$VM = get-wmiobject -namespace root\virtualization -Query "Select * From Msvm_ComputerSystem Where ElementName='$VMName'"
}
if ([IO.Directory]::Exists("$dest\TmpDir\$VMName"))
{
[IO.Directory]::Delete("$dest\TmpDir\$VMName", $True)
}
echo "Exporting the VM"
$status = $VM_Service.ExportVirtualSystem($VM.__PATH, $True, "$dest\TmpDir")
if ($status.ReturnValue -eq 4096)
{
$job = [Wmi]$status.Job
while (!($job.PercentComplete -eq 100) -and ($job.ErrorCode -eq 0))
{
Start-Sleep(5)
$job = [Wmi]$status.Job
echo $job.PercentComplete
}
}
## Store the files on in a temp directory before moving them to their location and then remove the old files.
if ([IO.Directory]::Exists("$dest\$VMName"))
{
[IO.Directory]::Move("$dest\$VMName", "$dest\$VMName-OldTmpDir")
[IO.Directory]::Move("$dest\TmpDir\$VMName", "$dest\$VMName")
[IO.Directory]::Delete("$dest\$VMName-OldTmpDir", $True)
}
else
{
[IO.Directory]::Move("$dest\TmpDir\$VMName", "$dest\$VMName")
}
echo "Done with $VMName"
$VM.RequestStateChange($VMReturnState)
}