Friday, October 11, 2013

HOWTO - Automatically restart Stopped Hyper-V VMs

I am currently studying SCCM 2012 and have created a small lab on 2008R2 with Hyper-v and two 2012  servers.

One is running my Domain Controler, DNS and DHCP and the other is my SCCM 2012 Primary Site server.

There is a small issue with this lab though is that my Hyper-V VMs keep shuting down every so often.
Checking the Event Viewer seems to indicate an issue with the licensing.

It seems that because I am using server 2012 in evaluation mode, once the grace periode has expired this is the standard behaviour. Of course I can use slmgr.vbs to rearm the grace period up to 5 times but then ...

So I added this little PowerShell code to my $profile to add an event that run a Start-Lab function to restart my VMs should they have stopped.

If you have not done so already, download the HyperV Module from Codeplex HERE, and ensure that you are have enabled your script execution policy as RempoteSigned or Unrestricted using this command:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Also ensure that you run PowerShell with elevated rights.

Enough preparation, lets dig into this short script:

#Manually create a Modules folder under your PS profile and add the HyperV module.
#C:\Users\Administrator\Documents\WindowsPowerShell\Modules\HyperV
#Add the HyperV cmdlet to this session
Import-Module HyperV

## Create an Timer instance 
$timer = New-Object Timers.Timer

## Now setup the Timer instance to fire events
$timer.Interval = 300000     # fire every 5mins
$timer.AutoReset = $True  # enable the event again after its been fired
$timer.Enabled = $true

## register your event
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier HyperV  -Action {Start-Lab}

# Start your timer
$timer.start

Function Start-Lab
{
#Use the get-vm STopped switch to return VMs that need restarting,
# filter them by name and restart if its a match.
get-vm -Stopped | %{if(($_.ElementName -eq "PS1") -or ($_.ElementName -eq "DC1"))
{Start-VM $_.ElementName} -Wait }
}

No comments:

Post a Comment