I have a PowerShell script running in an Azure Powershell task in VSTS, that starts several Azure virtual machines in a DevTest lab, but starts the domain controller first, waits for it to start, and then starts the others one after the other.
I'd like to start all the others in parallel and I tried to do this using Start-Job
but that spawns a new Powershell process which doesn't have the security context of the Azure login, so it fails. I'm trying something like this:
[cmdletbinding()]
param (
[ValidateSet("Start","Stop")][string]$Action,
$labName = "DevTestLab",
$labResourceGroup = "DevTestLabRG"
)
if ($Action -eq "Start") {
Write-Verbose "Starting the domain controller first"
Get-AzureRmResource | Where-Object {
$_.Name -match "dc" -and
$_.ResourceType -eq "Microsoft.Compute/virtualMachines" -and
$_.ResourceGroupName -match $labResourceGroup } | Start-AzureRmVM
Write-Verbose "Starting other machines in the lab as background jobs"
foreach ($AzureRMResource in Get-AzureRmResource |
Where-Object {
$_.Name -notmatch "dc" -and
$_.ResourceType -eq "Microsoft.Compute/virtualMachines" -and
$_.ResourceGroupName -match $labResourceGroup } )
{
Start-Job {
$myResource = $using:AzureRMResource
Start-AzureRMVM -Name $myResource.Name -ResourceGroupName $myResource.ResourceGroupName
}
}
# wait for all machines to start before exiting the session
Get-Job | Wait-Job
Get-Job | Remove-Job
}
I am using a Hosted Agent to run the script, so I can't have many agents running at once, and VSTS doesn't support parallel tasks as far as I am aware.
Any ideas on how to solve this?
-AsJob
switch help? docs.microsoft.com/en-us/powershell/module/azurerm.compute/… – user2226112