PowerShell Script to Log to Event Viewer and Reboot

We recently needed to create a PowerShell script to log to the event viewer and reboot the machine on a schedule.  This is what we came up with.

The PowerShell

$evt=new-object System.Diagnostics.EventLog("Application")
$evt.Source="itgroove Scheduled Reboot"
$infoevent=[System.Diagnostics.EventLogEntryType]::Information
$vdate=Get-Date
$val="itgroove Scheduled Reboot Event at: ["+$vdate+"]"
$evt.WriteEntry($val,$infoevent,70)
Restart-Computer –Force

You simply put this into a file (such as C:TOPSharePointreboot.ps1)

Basically, the script breaks down as this:

Line 1 – Choose the “Application” event log (you can see this in the screen capture below at the very top)
Line 2 – The event source (the name of the script logging the event – this can be whatever you want it to be)
Line 3 – This is just an Information event (as opposed to a Warning, Error, Critical)
Line 4 – Get the current date stamp
Line 5 – Assemble the line we’re going to log as the “details” of the event
Line 6 – Actually write the event to the log (the last parameter is the application specific Event ID – in our case we choose the number 70 – this is a number you choose as the writer of this script)
Line 7 – Reboot the machine

This is how it maps to the event viewer:

1 = $evt.Source="itgroove Scheduled Reboot" (line 2 in the code above)

2 = $val="itgroove Scheduled Reboot Event at: ["+$vdate+"]" (line 5 above)

3 = $evt.WriteEntry($val,$infoevent,70) (line 6 above)

image

The Shell Script

@ECHO OFF
ECHO Performing Reboot
POWERSHELL "& ‘C:TOPSharePointreboot.ps1’"

You simply put this into a file (such as C:TOPSharePointreboot.cmd)

The Schedule

The last step you have to do is add the above shell script (reboot.cmd) to the task scheduler, and you’re off to the races.