Start and Stop Azure VM’s in Parallel

Posted by

During a project I had to start and stop about 100 VMs, if I put the runbook in serial mode, it took about 2 hours to be execute, so… the only way to do it in a fast way, was to program the runbook to be executed in parallel mode. How can it be done? Easy!
#list and start vm with tag "OpeningHours" and value "7 to 19"
$vms = get-azvm | where {$_.Tags["OpeningHours"] -contains "7 to 16"}
$jobs = @()
foreach ($vm in $vms)
{
$job = Start-Job -ScriptBlock {
start-Azvm -Name $vm.name
}
$jobs = $jobs + $job
}
# Wait for it all to complete
Wait-Job -Job $jobs

That’s all, you can change the start-azvm with a stop-azvm -force and you will be done

2 comments

  1. Hi

    Thanks for this script.

    I’m quite new to Powershell and had a problem with it or 2 actually.

    Firstly it wouldn’t recognise the $vm.name in the ScriptBlock, I fixed this by replacing with $using:vm.name
    Then it prompted me for a resourcegroup.

    So ultimately I replaced
    start-Azvm -Name $vm.name
    with
    $using:vm | start-Azvm

    Hope this helps you / others.

    Thanks again

    Chris.

    I’m quite new to Powershell and had a problem with it or 2 actually.

    Firstly it wouldn’t recognise the $vm.name in the ScriptBlock, I fixed this by replacing with $using:vm.name
    Then it prompted me for a resourcegroup.

    So ultimately I replaced
    start-Azvm -Name $vm.name
    with
    $using:vm | start-Azvm

    Hope this helps you / others.

    Thanks again

    Chris.

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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