【问题标题】:Powershell with Shutdown command error handling带有关机命令错误处理的 Powershell
【发布时间】:2013-08-08 01:16:43
【问题描述】:

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

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"
}
}

【问题讨论】:

  • 在PowerShell 3.0中实际上有一个-Delay参数,但没有一个reason参数...
  • 您是否无法在关闭命令后使用 $lastexitcode 来检查非零返回码?如果发生 RPC 服务或其他错误时返回 0,我会感到惊讶(尽管我没有检查过)
  • PowerShell -Delay 参数不适用于延迟重启。相反,它“确定 Windows PowerShell 查询 For 参数指定的服务的频率,以确定它在计算机重新启动后是否可用。”默认为 5 秒。

标签: powershell shutdown


【解决方案1】:

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

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 的检查会触发成功/失败操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2016-03-13
    • 2018-10-31
    • 2019-11-15
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多