Share via


Starting Hyper-V virtual machines in sequence

This post describes a simple approach for scripting the startup of multiple Hyper-V virtual machines in sequence.


I do a lot of work with virtualized environments with Hyper-V virtual machines running in a Windows client operating system. I'll often have multiple VMs per environment, with startup dependencies between them. For example, a Team Foundation Server environment using domain authentication and a separate database tier will require 3 VMs, one for Active Directory, one for the SQL Server database, and one for the TFS application tier.

To serialize the startup of these virtual machines and ensure they start in a specific order, I've created the following PowerShell script:

 [CmdletBinding()]
Param(
    [Parameter(Position=0)]
    [array]$list = @("AD", "SQL", "TFS")
)

$start = Get-Date
Write-Output "$(Get-Date $start -Format g) => Starting the following VMs: $list"

foreach ($item in $list)
{
    $name = "HV-DEMO-" + $item
    Write-Output ""
    Write-Output "Starting VM: $name"
    Start-VM -Name $name
    Write-Output "Waiting for heartbeat..."
    Wait-VM -Name $name -For Heartbeat
    Write-Output "VM $name started and accepting connections"
}

$finish = Get-Date
Write-Output "$(Get-Date $finish -Format g) => Finished in $(($finish - $start).Minutes) minutes $(($finish - $start).Seconds) seconds"

Saving this script to a local file named "start-tfs-vms.ps1" and then running it with no parameters (uses the default parameter values) displays the following output:

   
 Windows PowerShell
 Copyright (C) Microsoft Corporation. All rights reserved.

 PS C:\> start-tfs-vms.ps1
 1/9/2018 6:11 PM => Starting the following VMs: AD SQL TFS

 Starting VM: HV-DEMO-AD
 Waiting for heartbeat...
 VM HV-DEMO-AD started and accepting connections

 Starting VM: HV-DEMO-SQL
 Waiting for heartbeat...
 VM HV-DEMO-SQL started and accepting connections

 Starting VM: HV-DEMO-TFS
 Waiting for heartbeat...
 VM HV-DEMO-TFS started and accepting connections

 1/9/2018 6:11 PM => Finished in 0 minutes 42 seconds  

You can easily create another script named "stop-tfs-vms.ps1" that replaces usage of the Start-VM cmdlet with the Stop-VM cmdlet to reverse this operation. Note that you will probably want to change the order of the VM names so they stop in the reverse order.