Friday, October 05, 2012

How to start/stop Hyper-V machines with PowerShell

Being a Hyper-V fan, I try to keep all of my VM’s named and line up correctly.  The problem is that with so many versions of SharePoint, SQL, OS.  The management of those VM’s can get a bit tricky.  For instance, I have 3 SharePoint farms that I might need to run at one point or another.  The problem that I had, was that I wanted to start a farm or a set of vm’s with a single script.  Well, trying to start up all of your vm’s at once creates a problem when you try to start a SharePoint farm.

The dependencies for SharePoint is that the SQL server needs to be up and running as well as the Domain controller.  For the SQL Server to start, it needs the Domain controller to be up and running.  So somehow, you need to start the AD, wait for it to be up and running before starting the SQL, and then finally when both are running, then you can start your SharePoint server.  This sequence does not allow you to get a cup of coffee while all of the vm’s are starting.  You need to monitor the state of each server before  moving to the next one.

The workflow will be something like this:  AD –>  SQL –> SharePoint

Now, enter PowerShell.  With PowerShell, I have several scripts that will perform this workflow correctly.  If you are still running Windows Server 2008-R2 as your desktop machine (and who isn't, right?), you can download the Powershell Management Library for Hyper-V in Codeplex.  This module is necessary, even if you are running PowerShell v3.

hyperV

Here is my script to start up the VM machines.  Noticed that I’m using the HearBeatTimeOut.  This parameter waits for the OS to be up and running before the next command is executed!
Import-Module "C:\Program Files\modules\HyperV\HyperV.psd1"

start-vm "DemoAD" -HeartBeatTimeOut 300
start-vm "DemoSQL2008" -HeartBeatTimeOut 300
start-vm "DemoWFE1" -HeartBeatTimeOut 300

and the script to stop them.  It is always nice to use the reason parameter. This parameter is needed so that I don’t have to explain WHY it was shutdown when starting the VM’s.
Import-Module "C:\Program Files\modules\HyperV\HyperV.psd1"

shutdown-vm "DemoWFE1" -force -reason "end of day"
shutdown-vm "DemoSQL2008" -force -reason "end of day"
shutdown-vm "DemoAD" -force -reason "end of day"

now, where is that cup of coffee… :)