My shutdown script using the Shutdown -R
command to do a mass reboot of machines. If the Shutdown -R
throws a error like "RPC Service Unavailable, or access denied" I can't catch it or just don't know how to. Can someone help? I don't want to use Restart-Computer in powershell since you can't delay the reboot and can't add comments.
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"
}
}
If PowerShell Remoting is enabled on $PC
something like this might work:
Invoke-Command -Computer $PC { shutdown /r /f /d p:1:1 /t 300 /c $ARGV[0] } `
-ArgumentList $reboot_reason
The -Computer
option takes an array of names/IPs.
If you want to stick with your approach and just catch errors from shutdown.exe
, evaluate $LastExitCode
after the command:
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
suppresses the actual error message, and the check on $LastExitCode
triggers the success/failure action.