0

我的关机脚本使用Shutdown -R命令对机器进行大规模重启。如果Shutdown -R抛出诸如“RPC 服务不可用或访问被拒绝”之类的错误,我无法捕捉到它,或者只是不知道如何捕捉。有人可以帮忙吗?我不想在 powershell 中使用 Restart-Computer,因为你不能延迟重启,也不能添加评论。

foreach($PC in $PClist){
ping -n 2 $PC >$null
if($lastexitcode -eq 0){
  write-host "Rebooting $PC..." -foregroundcolor black -backgroundcolor green
  shutdown /r /f /m \\$PC /d p:1:1 /t 300 /c "$reboot_reason"
  LogWrite "$env:username,$PC,Reboot Sent,$datetime"
} else {
  write-host "$PC is UNAVAILABLE" -foregroundcolor black -backgroundcolor red
  LogWrite "$env:username,$PC,Unavailable/Offline,$datetime"
}
}
4

1 回答 1

3

如果在类似这样的东西上启用了 PowerShell 远程处理$PC可能会起作用:

Invoke-Command -Computer $PC { shutdown /r /f /d p:1:1 /t 300 /c $ARGV[0] } `
    -ArgumentList $reboot_reason

-Computer选项采用名称/IP 数组。

如果您想坚持您的方法并从 中捕获错误,请在命令之后shutdown.exe进行评估:$LastExitCode

shutdown /r /f /m \\$PC /d p:1:1 /t 300 /c "$reboot_reason" 2>$null
if ($LastExitCode -ne 0) {
  Write-Host "Cannot reboot $PC ($LastExitCode)" -ForegroundColor black `
      -BackgroundColor red
} else {
  LogWrite "$env:username,$PC,Reboot Sent,$datetime"
}

2>$null抑制实际的错误消息,并且检查$LastExitCode触发成功/失败操作。

于 2013-08-07T17:07:22.720 回答