如何在 Azure 自动化的 PowerShell 工作流中中断 ForEach 循环?
附加信息:
我在 Azure 自动化中有一个 VM 恢复运行手册,它遍历附加的数据磁盘。每个 VHD 的 blobcopy 备份的名称正在使用数组输入到 Runbook,并与要还原的当前数据磁盘匹配。
备份的名称采用以下格式:MM-DD-YYYY--BlobName.vhd
例子:
数据盘名称:TestDisk-1.vhd
备份名称:12-22-2014--TestDisk-1.vhd
对于每个数据磁盘,正在运行这段代码:
$dataDisksRestored = 0
ForEach ( $vmDataDisk in $vmDataDisks ) {
$vmDataDiskName = $vmDataDisk.DiskName
$vmDataDiskuris = $vmDataDisk.MediaLink
$vmDataBlobName = $vmDataDiskuris.Segments[-1]
$vmDataOrigContainerName = $vmDataDiskuris.Segments[-2].Split('/')[0]
$attached = $false
While ($attached -eq $False) {
if ((Get-AzureDisk -DiskName $vmDataDiskName).AttachedTo) {
Write-Output "Sleeping for 5"
Start-Sleep 5
} else {
$attached = $true
}
}
$dataDiskBlobBackupName = $null
ForEach ($backupName in $vmDataDisksBackupNames) {
$b = $backupName.Split('-')[-1]
Write-Output $b
Write-Output $vmDataBlobName
if ($b.CompareTo($vmDataBlobName) -eq 0) {
$dataDiskBlobBackupName = $backupName
break # <- *** Break here if the names match ***
}
}
#Remove-AzureDisk -DiskName $vmDataDiskName –DeleteVHD
#Start-AzureStorageBlobCopy -SrcContainer $backupContainerName -SrcBlob $dataDiskBlobBackupName -DestContainer $vmDataOrigContainerName -DestBlob $vmDataBlobName –Force
#Get-AzureStorageBlobCopyState -Container $vmDataOrigContainerName -Blob $vmDataBlobName –WaitForComplete
#Add-AzureDisk -DiskName $vmDataDiskName -MediaLocation $vmDataDiskuris.AbsoluteUri
$dataDisksRestored++
}
我得到的错误是:
Runbook definition is invalid. Break and Continue statements are not supported in a Windows
PowerShell Workflow. Instead, use an 'if' statement to control loop execution.
我认为添加检查以查看 $dataDiskBlobBackupName 是否仍为 null 将阻止代码块的其余部分运行,但它仍会循环遍历数组的其余部分。有没有更简单的方法来打破循环?