Looping Get-VM

Mar 12, 2009 at 2:46 PM
I'm looking at putting together a couple of rough backup scripts for my HyperV box, but was looking for an example of looping through the output from Get-VM. For example, I want to call Get-VM -state Running, suspend the VM's, export, and restart them - without starting any that were not already running!

Mar 16, 2009 at 3:01 PM
you should be able to do
$myVms=Get-VM -Running
Suspend-VM $myVMS

$myVms | foreach-Object {dostuff -parameter $_}

Start-VM $myVMS

Oct 5, 2009 at 1:26 PM
Edited Oct 5, 2009 at 1:27 PM

@Jamesone: I am not sure if the answer you gave it is what the question is looking for.


The challenge is the fact that the SUSPEND-VM command is already released but in the background the HyperV server is still busy suspending the machine. So the script should wait untill the GET-VM states "SUSPENDED" instead of "SAVING"


I also did some research but i could not figure it out... can you/anyone help me out?




Set-ExecutionPolicy unrestricted
. D:\INSTALL\hyperv-scripts\hyperv.ps1

# suspend VM
start-vm PR-VM-07
suspend-VM PR-VM-07

# begin loop

  if(get-vm pr-vm-07 | select-string -pattern "Saving")
    # Still saving
    write-host "Still saving, script sleeping"
    Sleep 2

  if(get-vm pr-vm-07 | select-string -pattern "Suspended")
    # Suspended
    # Backup machine
    write-host "Suspending finished and ready for backup"



Oct 31, 2009 at 5:09 PM

sorry, I should have said suspend-vm $myVMs -wait