0

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"
}
}
3
  • In PowerShell 3.0 there is actually a -Delay parameter, but not a reason parameter... Commented Aug 7, 2013 at 16:05
  • 1
    Are you unable to use $lastexitcode after your shutdown command to check for a non-zero return code? I would be surprised if it returns 0 when an RPC Service or other error occurs (though I haven't checked this) Commented Aug 7, 2013 at 16:09
  • The PowerShell -Delay parameter is not for delaying the reboot. Instead it "Determines how often Windows PowerShell queries the service that is specified by the For parameter to determine whether it is available after the computer is restarted." Default is 5 seconds. Commented Sep 29, 2015 at 2:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.