Powershell关闭VM脚本

时间:2016-02-18 06:13:31

标签: powershell

我有一个脚本可以根据输入到数组中的名称关闭vms。

该部分工作正常,但是在关闭启动后的下一部分应该等待一段时间,并通知它等待关闭的有多少个vms,然后再转到另一个关闭其他vms的阶段。

我没有从阵列中获取任何vms。以下是特定阶段的代码:

$waittime = 5 #Seconds

#Create Phase 1 Array
[Array] $PHASE1 = "TestSvr2008"

# For each of the VMs on the Hyperv hosts that are powered on
Foreach ($VM in ($PHASE1 | %{ Get-VM | Where { $_.State -eq "Running" }})){
    # Shutdown the guest cleanly
    $VM | Stop-VM -Confirm:$false }

    # Set the amount of time to wait before assuming the remaining powered on guests are stuck
$waittime = 120 #Seconds

$Time = (Get-Date).TimeofDay
do {
    # Wait for the VMs to be Shutdown cleanly
    sleep 1.0
    $timeleft = $waittime - ($Newtime.seconds)
    $numvms = ($PHASE1 | %{ Get-VM | Where { $_.$VM -eq $PHASE1 }}).Count
    Write "Waiting for shutdown of $numvms VMs or until $timeleft seconds"
    $Newtime = (Get-Date).TimeofDay - $Time
    } until ((@($PHASE1 | %{ Get-VM | Where { $_.$VM -eq $PHASE1 }}).Count) -eq 0 -or ($Newtime).Seconds -ge $waittime)

由于

1 个答案:

答案 0 :(得分:0)

dountil块中的这一行存在问题:

$numvms = ($PHASE1 | %{ Get-VM | Where { $_.$VM -eq $PHASE1 }}).Count
  • $_.$VM是拼写错误,应为$_.VM
  • $_.VM -eq $PHASE1尝试检查VM名称是否等于数组。比较不会这样。
  • ForeEach-Object是不必要的

Get-Vm通过管道或直接作为Name参数接受VM名称数组。所以你可以这样做:

$numvms = ($PHASE1 | Get-VM).Count

$numvms = (Get-VM -Name $PHASE1).Count