1

For an example I have 3 virtual machines in a Resource Group.

I want to Start those virtual machines in parallel.

Lets say, 1 VM takes 3 mins to Start, so for 3 VMs it would take 9 mins. Now I want those VMs to start in parallel such that in around 3 mins all the 3 VMs should get started.

After much R&D I didn't find any solution.

Thank You.

Bunty Thakkar
  • 73
  • 1
  • 10

1 Answers1

1

You can use Start-Job and Wait-Job to implement this. Here is a PowerShell script for you.

$cred = Get-Credential
$VMs = @(@{"Name"="vm1";"ServiceName"="srv1"};@{"Name"="vm2";"ServiceName"="srv2"};@{"Name"="vm3";"ServiceName"="srv3"})
$jobs = @()
foreach ($vm in $VMs) 
{ 
    $params = @($vm.Name, $vm.ServiceName, $cred) 
    $job = Start-Job -ScriptBlock { 
        param($Name, $ServiceName, $cred) 
        try{
            $acct = Get-AzureRmSubscription
        }
        catch{
            Login-AzureRmAccount -Credential $cred
        }
        start-AzureVM -Name $Name -ServiceName $ServiceName 
    } -ArgumentList $params  
    $jobs = $jobs + $job 
} 
Wait-Job -Job $jobs
Get-Job | Receive-Job

The above code is for classic deployed VMs. If you are using ARM deployment, you can use the following script instead.

$cred = Get-Credential
$VMs = @(@{"Name"="vm1";"ResourceGroupName"="rg1"};@{"Name"="vm2";"ResourceGroupName"="rg2"};@{"Name"="vm3";"ResourceGroupName"="rg3"})
$jobs = @()
foreach ($vm in $VMs) 
{ 
    $params = @($vm.Name, $vm.ResourceGroupName, $cred) 
    $job = Start-Job -ScriptBlock { 
        param($Name, $ResourceGroupName, $cred) 
        try{
            $acct = Get-AzureRmSubscription
        }
        catch{
            Login-AzureRmAccount -Credential $cred
        }
        start-AzureRmVM -Name $Name -ResourceGroupName $ResourceGroupName 
    } -ArgumentList $params  
    $jobs = $jobs + $job 
} 
Wait-Job -Job $jobs
Get-Job | Receive-Job
Jack Zeng
  • 2,257
  • 12
  • 23
  • I tried running the script, but it seems that the VMs are getting started one after the other in a loop, and why does I have to Login-AzureRmAccount for every loop. ??? – Bunty Thakkar Feb 02 '16 at 09:12
  • How did you know the VMs start one after another? Did you see it on the portal? I have tested a script with `Login-AzureRmAccount` out side of the loop, but it only work for the first VM. And, you can see that, the `Login-AzureRmAccount` is surrounded by try-and-catch, so, if it's already login, it will not login again. – Jack Zeng Feb 02 '16 at 09:58
  • You have to Login-AzureRMAccount in each job because each job is in a separate process (requiring it's own authn). PS didn't always work this way but it does with the new 1.x cmdlets. So the try/catch is probably unnecessary there... – bmoore-msft Feb 02 '16 at 18:07
  • @JackZeng Thanks a lot. I am done with what i wanted. :) – Bunty Thakkar Feb 03 '16 at 09:35
  • @bmoore-msft Thanks!! I got it. – Bunty Thakkar Feb 03 '16 at 09:35