我有一个powershell脚本,可以使用Jenkins在特定时间并行停止/启动VM。此脚本使用-AsJob powershell cmdlet,这样VM会显示它们在Jenkins输出中停止,但实际上它们正在Azure门户中取消分配。
我还有一个5分钟的睡眠定时器来获取Get-AzureRmVM -Status命令。
问题: - 有没有办法将其循环到可以检查虚拟机状态的位置,如果虚拟机未处于“已分配”或“正在运行”状态,则脚本会在另一分钟左右进行检查。一旦VM最终处于解除分配或运行状态,脚本/作业就会成功退出。
代码段
$JobList = @()
foreach ($VM in $vms)
{
if ($env:OPTION -eq "start")
{
Write-Output "Starting :- $($VM.Name) in $($VM.ResourceGroupName)"
$JobList += Start-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -AsJob -Verbose
Write-Output "$($VM.Name) has started successfully `n"
Write-Output "--------------------------------------------------"
}
elseif ($env:OPTION -eq "stop")
{
Write-Output "Deallocating :- $($VM.Name) in $($VM.ResourceGroupName)"
$JobList += Stop-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -AsJob -Verbose
Write-Output "$($VM.Name) has been deallocated successfully `n"
Write-Output "--------------------------------------------------"
}
else
{
Write-Output "ERROR!!! No option selected, select an option"
}
}
sleep 300
Write-Output "`n##############################################"
Write-Output "### Writing Status of VMs to Workspace ###"
Write-Output "##############################################"
Get-AzureRmVM -Status | Where-Object {($_.tags.ManagedBy -eq "blaah") -And ($_.tags.Environment -eq "stage")}
编辑 - 此代码检查VM的状态以查看是否已取消分配。我无法让它再次运行循环,因为虚拟机处于运行状态。
$vms = (Get-AzureRmResource | Where-Object {($_.tags.ManagedBy -eq "blaah") -And ($_.tags.Environment -eq "Stage")}
foreach ($VM in $VMs) {
$vmDetail = Get-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -Status
foreach ($vmDetail in $vmDetail.Statuses[1]) {
$VMStatusDetail = $vmDetail.DisplayStatus
if ($VMStatusDetail -ne "Stopped") {
Write-Output "Waiting for $($VM.Name) to deallocate"
Write-Output "State:- $($VM.Name) is $VMStatusDetail"
start-sleep -s 5
}
else {
Write-Output "State:- $($VM.Name) is $VMStatusDetail"
}
}
}
答案 0 :(得分:0)
如果将Stop-AzureRMVM作为Jobs并把输出保存在名为$ JobList的Jobs数组中,则所有作业启动后,在循环的末尾和循环外,您可以添加以下命令以等待作业完成。 / p>
Write-Host $JobList
$JobList| Get-Job | Wait-Job | Receive-Job | Format-Table -AutoSize