次の方法で共有


Windows Azure, PowerShell: How to start virtual machines in parallel

In Windows Azure, I sometimes have several virtual machines that are part of the same vNet but are spread across different cloud services. Several VMs in the same cloud service are not started in parallel,. However, I have several cloud services so I may want to deploy in parallel my VMs from one script.

In my example, I want to start the following VMs in the same vNet:

image

They will be part of the following cloud services:

image

image

image

So I thought of foreach-parallel and found this thread in stackoverflow:

https://stackoverflow.com/questions/4016451/can-powershell-run-commands-in-parallel

This lead me to the following script:

'deswebsvm', 'deswebsIIS', 'deswebstomcat' | %{
    echo $_

    $scriptBlock = {
        param($serviceName)

        Import-Module azure

        $subscription = 'xxx'
        Set-AzureSubscription -SubscriptionName $subscription -CurrentStorageAccount 'xxx'
        Set-AzureSubscription -DefaultSubscription $subscription

        $allvms = Get-AzureVM -ServiceName $serviceName
        $allvms | select name
        $allvms | Start-AzureVM
    }

    Start-Job $scriptBlock -ArgumentList $_
}

# Wait for it all to complete
While (Get-Job -State "Running")
{
    Start-Sleep 10
    echo '---------------------------'
    Get-Job
}

# Getting the information back from the jobs
Get-Job | Receive-Job

Remove-Job *

With this, I have virtual machines starting in cloud services deswebsvm, deswebsiis and deswebstomcat in parallel.

In order to stop the same VMs, I have the following script:

'deswebsvm', 'deswebsIIS', 'deswebstomcat' | %{
    echo $_

    $scriptBlock = {
        param($serviceName)

        Import-Module azure

        $subscription = 'xxx'
        Set-AzureSubscription -SubscriptionName $subscription -CurrentStorageAccount 'xxx'
        Set-AzureSubscription -DefaultSubscription $subscription

        $allvms = Get-AzureVM -ServiceName $serviceName
        $allvms | select name
        $allvms | Stop-AzureVM -Force
    }

    Start-Job $scriptBlock -ArgumentList $_
}

# Wait for it all to complete
While (Get-Job -State "Running")
{
     Start-Sleep 10
    Get-Job
}

# Getting the information back from the jobs
Get-Job | Receive-Job

Remove-Job *

Smile

Benjamin Guinebertière (@benjguin)