Citrix Hypervisor PowerShell – Reset VM

This XenServer PowerShell script resets a XenServer VM by doing the following:

  • Shuts down the VM down and waits for the VM to power off
  • Reverting to the “Baseline” snapshot (creates one if one not already created)
  • Starts the VM
  • Waits for VM to be in a running state, (waits until the VM’s Netlogon Windows service is running)
function Reset-XenServerVM {
    [string] $Server
        #Power off VM
        $ServerVM = get-xenvm -name $Server
        Do {
            if ($ServerVM.power_state -ne "Halted") {
                #shut down VM
                Invoke-XenVM -VM $ServerVM -XenAction Shutdown -async
                Write-host (date -Format hh:mm:ss)   -   Waiting for $Server to shutdown -ForegroundColor Yellow
                sleep 10
                $ServerVM = get-xenvm -name $Server
        } while ($ServerVM.power_state -ne "Halted")

        # create baseline snapshot on VM if one doesn't exist
        $snapshotname = "Baseline"
        $ServerVM = get-xenvm -name $Server
        $Snapshot = Get-xenvm -name $snapshotname | where { $_.snapshot_of -eq $ServerVM} -ErrorAction SilentlyContinue
        If ($snapshot -eq $null) {
            Write-host (date -Format hh:mm:ss)   -   Creating Snapshot $snapshotname for VM $Server -ForegroundColor Yellow
            Invoke-XenVM -VM $ServerVM -XenAction Snapshot -NewName $SnapShotName

        #Revert to baseline snapshot on VM
        Write-host (date -Format hh:mm:ss)   -   Reverting $Server to $snapshotname snapshot -ForegroundColor Yellow
        $ServerVM = get-xenvm -name $Server
        $Snapshot = Get-xenvm -name $snapshotname | where { $_.snapshot_of -eq $ServerVM}
        Invoke-XenVM -VM $ServerVM -XenAction Revert -Snapshot $snapshot

        #Start VM
        Write-host (date -Format hh:mm:ss)   -   Starting VM $Server  -ForegroundColor Yellow
        $ServerVM = get-xenvm -name $Server
        Invoke-XenVM -vm $ServerVM -XenAction start

        #Wait for VM to boot
        do {
            Write-host (date -Format hh:mm:ss)   -   Waiting for VM $Server to boot -ForegroundColor Yellow
            $VMServices = get-service -ComputerName $Server -name Netlogon -ErrorAction SilentlyContinue
            sleep 30
        } until ($vmservices.status -like "running")


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.