2013-08-07 43 views
0

我的关机脚本使用Shutdown -R命令来执行机器的大量重新引导。如果Shutdown -R引发错误,如“RPC服务不可用,或访问被拒绝”,我无法捕捉它或只是不知道如何。有人可以帮忙吗?我不想在PowerShell中使用Restart-Computer,因为您无法延迟重新启动并且无法添加注释。Powershell with Shutdown命令错误处理

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

在PowerShell 3.0中,实际上有一个-Delay参数,但不是一个原因参数... –

+1

您是否无法在您的shutdown命令之后使用$ lastexitcode来检查非零返回码?如果RPC服务或其他错误发生时返回0,我会感到惊讶(虽然我没有检查过) –

+0

PowerShell -Delay参数不是用于延迟重新启动。而是“确定Windows PowerShell查询由For参数指定的服务的频率,以确定计算机重新启动后它是否可用”。默认值是5秒。 –

回答

2

如果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检查触发成功/失败的行动。