重新启动计算机并显示日志或结果

问题描述 投票:0回答:1

我需要同时重新启动 5 或 6 台计算机。 它与命令

restart-computer
配合使用效果很好。但我想添加
-wait
以确保每个服务器都已重新启动。

所以,我当然可以这样做:

foreach ($VMs in $Servers){
    restart-computer $Servers -force -wait
    Write-Output "$vms has been rebooted"
}

我尝试过

-asjob
,但我不太明白它是如何工作的以及如何得到结果。另外,这意味着我不能再使用
-wait
了。

有没有办法将

restart-computer
的结果导出到日志或数组中?
我如何知道其中一台服务器是否无法重新启动,如果是这种情况,脚本是否会继续运行?

powershell restart
1个回答
0
投票

Restart-Computer
不提供自己的输出。
也就是说,你可以简单地做类似的事情

# Creates string list to collect the logs
$RestartLog = [System.Collections.Generic.List[object]]@()

foreach ($VM in $VMList) {
    # restarts $VM, by force, waits for Powershell to be available, checks every 2 seconds for a total of 300 seconds(5minutes) 
    # if you do not set -Timeout, it will wait forever
    # if the computer doesn't answer before the Timeout is reached, the command goes on.
    Restart-Computer $VM -Force -Wait -For PowerShell -Timeout 300 -Delay 2 -WhatIf

    # Prepares Log line
    $RestartLine = 'Computer {0} has been restarted at {1}' -f $VM, (Get-Date)

    # add string to list
    $RestartLog.Add($RestartLine)

    # optional: write it to the screen
    Write-Host $RestartLine
}

# append list to log file
$RestartLog | Out-File -FilePath $FileLog -Append
© www.soinside.com 2019 - 2024. All rights reserved.