#Requires -Version 3.0
#Requires -Module AzureRM.Resources
param
(
[Parameter(Mandatory=$false, HelpMessage="Name of the subscription that has the lab")]
[string] $SubscriptionName,
[Parameter(Mandatory=$false, HelpMessage="Lab name")]
[string] $LabName
)
# Connect and add the appropriate subscription
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationID $Conn.ApplicationId -Subscription $SubscriptionName -CertificateThumbprint $Conn.CertificateThumbprint
# Find the lab
$dtLab = Find-AzResource -ResourceType 'Microsoft.DevTestLab/labs' -ResourceNameEquals $LabName
# Get the VMs
$dtlAllVms = New-Object System.Collections.ArrayList
$AllVMs = Get-AzResource -ResourceId "$($dtLab.ResourceId)/virtualmachines" -ApiVersion 2016-05-15
# Get the StartupOrder tag. If missing, set to start up last (10).
ForEach ($vm in $AllVMs) {
if ($vm.Tags) {
if ($vm.Tags['StartupOrder']) {
$startupValue = $vm.Tags['StartupOrder']
} else {
$startupValue = 10
}
} else {
$startupValue = 10
}
$dtlAllVms.Add(@{$vm.Name = $startupValue}) > $null
}
# Setup for the async multiple vm start
# Save profile
$profilePath = Join-Path $env:Temp "profile.json"
If (Test-Path $profilePath){
Remove-Item $profilePath
}
Save-AzContext -Path $profilePath
# Job to start VMs asynch
$startVMBlock = {
Param($devTestLab,$vmToStart,$profilePath)
Import-AzContext -Path ($profilePath)
Invoke-AzResourceAction `
-ResourceId "$($devTestLab.ResourceId)/virtualmachines/$vmToStart" `
-Action Start `
-Force
Write-Output "Started: $vmToStart"
}
$current = 0
# Start in order from 0 to 10
While ($current -le 10) {
# Get the VMs in the current stage
$tobeStarted = $null
$tobeStarted = $dtlAllVms | Where-Object { $_.Values -eq $current}
if ($tobeStarted.Count -eq 1) {
# Run sync – jobs not necessary for a single VM
$returnStatus = Invoke-AzResourceAction `
-ResourceId "$($dtLab.ResourceId)/virtualmachines/$($tobeStarted.Keys)" `
-Action Start `
-Force
Write-Output "$($tobeStarted.Keys) status: $($returnStatus.status)"
} elseif ($tobeStarted.Count -gt 1) {
# Start multiple VMs async
$jobs = @()
Write-Output "Start Jobs start: $(Get-Date)"
# Jobs
$jobs += Start-Job -ScriptBlock $startVMBlock -ArgumentList $dtLab, $($singlevm.Keys), $profilePath
Write-Output "Start Jobs end: $(Get-Date)"
}
# Get results from all jobs
if($jobs.Count -ne 0) {
Write-Output "Receive Jobs start: $(Get-Date)"
foreach ($job in $jobs){
$jobResult = Receive-Job -Job $job -Wait | Write-Output
}
Remove-Job -Job $jobs -Force
}
else
{
Write-Output "Information: No jobs available"
}
}