gpt4 book ai didi

azure - 如何使用 powershell 等待操作完成

转载 作者:行者123 更新时间:2023-12-03 02:58:18 25 4
gpt4 key购买 nike

我有一个脚本可以在特定时间启动/停止虚拟机。问题是,我希望脚本仅在所有虚拟机启动/运行或释放/停止时退出。我当前的问题是,当虚拟机启动时,它会等到启动后才转到下一个虚拟机。

例如:vm1 正在启动.. vm2 正在启动.. vm3 正在启动..

vm1 is now running..
vm2 is still starting
vm3 is still starting

vm1 is now running..
vm2 is now running..
vm3 is now running..

然后脚本退出。

完整脚本在这里

$ACTION="开始"

Write-Output "Number of Virtual Machines: $($GetVMS.Name.Count)" `n
$GetVMS | Format-Table

$startstopvm = {

$ResourceGroupName = $args[0]
$Name = $args[1]
$ACTION = $args[2]

# Get VM status
try {
$VMs = Get-AzureRmVM -Name $Name -ResourceGroupName $ResourceGroupName -Status -WarningAction SilentlyContinue
} catch {
Write-Output ("Cloud not get vm $Name in $ResourceGroupName")
$Error[0]
Exit 1
}

if ($ACTION -eq "start")
{
foreach ($VM in $VMs)
{
if ($VM.Statuses[1].Code -eq "PowerState/running")
{
Write-Output ($VM.Name + " in " + $VM.ResourceGroupName + " is already running")
}
else
{
# The VM needs to be started
Write-Output ("Starting VM " + $VM.Name)
$startVM += Start-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -AsJob -ErrorAction Continue

$startTime = Get-Date

$timeElapsed = $((Get-Date) - $startTime).TotalMinutes

while ($timeElapsed -lt 2)
{
$startVM = Get-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -Status -WarningAction SilentlyContinue

if ($startVM.Statuses[1].Code -match "PowerState/(running|starting)")
{
# The VM started, so send notice
Write-Output ($VM.Name + " in " + $VM.ResourceGroupName + " has been started`n")
break
}
Start-Sleep -s 30
}

if ($getStat.Statuses[1].Code -ne "PowerState/(running|starting)")
{
# The VM failed to start, so send notice
Write-Output ($VM.Name + " failed to start`n")
}
}
}
}

注意:我正在从文件中读取虚拟机名称和 RG

try {
$VMList = Get-Content C:\Users\local\Desktop\VMs.csv | ConvertFrom-Csv
} catch {
Write-Output ("Cannot open file...")
exit -1
}

$Result = @()

foreach ($vm in $VMList) {
Invoke-Command -ArgumentList $vm.ResourceGroupName, $vm.Name, $ACTION -Verbose -ScriptBlock $startstopvm
}

最佳答案

我过去执行此操作的最简单方法是在 Start-Process cmdlet 上使用 -Wait 参数。

您应该能够通过较小的更改来实现这一点。

将当前代码块保存到单独的 .ps1 中,即 startstopvm.ps1

然后您可以更改 Invoke-Commmand 行以读取如下内容:
Invoke-Command -ArgumentList $vm.ResourceGroupName、$vm.Name、$ACTION -Verbose -ScriptBlock {启动进程 powershell.exe -Argument "C:\Scripts\Backup.ps1 TestBackup"-Wait}

肯定还有其他方法可以做到这一点,但这样的方法一直对我有用

关于azure - 如何使用 powershell 等待操作完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51331672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com