Powershell Commands - Reboot Computer

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 10 months, 1 week ago.

  • Author
    Posts
  • #34670
    Profile photo of Kenny B
    Kenny B
    Participant

    I am new to PowerShell, please bear with me. I was able to create a script to restart a computer and send email. I also setup to stop if it gets an error. (Ex. If computer is not on)

    My question is there a way to create a PowerShell script to not email if the reboot command does not work then process the next command which is to restart another computer. The erroraction stops the entire script. Would it be better to create a script for each computer. I want to reboot 7 computers in one script and run in task scheduler.

    restart-computer -computername "COMPUTER01" -force -wait -for wmi -delay 10 -erroraction stop
    send-mailmessage -to "EMAILADDRESS" -from ANYNAME@GMAIL.COM -subject "Computer01 RESTARTED" -smtpserver "MAILSERVERNAME"
    restart-computer -computername "COMPUTER02" -force -wait -for wmi -delay 10 –erroraction stop
    send-mailmessage -to "EMAILADDRESS" -from ANYNAME@GMAIL.COM -subject "Computer02 RESTARTED" -smtpserver "MAILSERVERNAME"

  • #34671
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Sure. You need a loop. Let's say you create a text file, named c:\computers.txt, which lists one computer name per line.

    ForEach ($computer in (Get-Content c:\computers.txt)) {
      Try {
        Restart-Computer -comp $computer -force -wait -for wmi -delay 10 -ea stop
        Send-MailMessage ...insert your parameters here...
      } Catch {
        Write-Warning "$computer did not restart"
      }
    }
    

    -EA (-ErrorAction) won't stop the script if it's in a Try{} block; it'll skip to the Catch{} block, and then keep going.

    I'll heartily recommend my books, "Learn PowerShell in a Month of Lunches" and "Learn PowerShell Toolmaking in a Month of Lunches" as great ways to learn this stuff ;).

You must be logged in to reply to this topic.