Starting up and Shutting down a list of VM’s in a specific order


A friend asked me if this was hard to do with PowerShell in Hyper-V.   He tapped me on the back and literally asked….

“When I have to shutdown a pile of Virtual servers for maintenance, I have a particular order they need to shutdown in, then startup needs to be the reverse.  Is there a nice easy way to do this in PowerShell?”

So I thought about it.   We could do this with one script actually (Which is the neat bit)

First let’s keep this simple.  I want a simple array of Servers.   We can do this in the following manner.

[array]$VMList=(‘Server1’,’Server2’,’Server3’,’Server4’)

With a list like this I can just step through them with PowerShell and Shutdown them in the order provided with a simple ForEach Loop

Foreach ($VM in $VMList)
{
Stop-VM –vm $VM
}

Now the second challenge …. REVERSING the order.  I was going to try and come up something really neat for this by getting count of elements in the array when I ran across this PowerTip from www.scriptingguys.com on Reverse an Array with PowerShell.

So to get the REVERSE order I just pass my Array into the Reverse method like this.

[array]::reverse($VMList)

Now I can run a SIMILIAR loop to Start the Virtual Machines.

Foreach ($VM in $VMList)
{
Start-VM –vm $VM
}

 

Cool.   Now I just need some way to tell the script whether I starting or stopping.   For this I can just drop in a Switch as a paramater and tell it to default to Stopping until specified.

 

param(
[switch]$Start=$True
)

 

At this point we can’t get fancy and maybe pop the $array of Servers as a parameter.   With a little IF Then Else to trap for the Switch our script looks a little like this

param(
[switch]$Start=$True,
[array]$VMlist=(‘Server1′,’Server2′,’Server3′,’Server4′,’Server5’)
)

if ($Stop)
{
    Foreach ($VM in $VMlist)
    {
    Stop-VM -VM $VM
    }
}

Else
{
    [array]::Reverse($vmlist)

    Foreach ($VM in $VMlist)
    {
    Start-VM -VM $VM
    }
}

 

Pretty neat what you can put together with just a little bit of Powershell eh?

Remember, with Great PowerShell comes Great Responsibility

Sean – The Energizedtech – Honorary Scripting Guy – MVP

Follow

Get every new post delivered to your Inbox.

Join 3,832 other followers