As promised, here is the safe restart PowerShell script version that includes writing output to the Event Log.
I used the Write-Eventlog command to get the output into the event log. I started by defining the variables. The eventID and eventSource can be anything, eventLog and eventType need to match the parameters of the Write-Eventlog command.
#eventlog vars $eventLog = "System" $eventType = "Information" $eventID = 212 $eventSource = "SafeRestart"
Next, I checked if the event source exists on the computer and if not, create it.
if (!(Get-Eventlog -LogName $eventLog -Source $eventSource)){ New-EventLog -LogName $eventLog -Source $eventSource }
Lastly, I added the Write-Eventlog command and variables to the script so it creates a message when one of the actions are ran. Below is the output of one of he messages.
Write-Eventlog -LogName $eventLog -Source $eventSource -EntryType $eventType -EventID $eventID -Message "Will not reboot, outside of maintenance hours"
Here is the finished version of the script:
#v2 adds writing output to the event log #eventlog vars $eventLog = "System" $eventType = "Information" $eventID = 212 $eventSource = "SafeRestart" #declare the day of the month for a reboot [int]$rebootDay = 22 #set the minimum days before reboot [int]$rebootAge = 1 #get the current day of the month and hour [int]$hour = get-date -format HH [int]$day = get-date -format dd #get the number of days the server has been running. Returns "0" if less than 24 hours $os=Get-WmiObject win32_operatingsystem $uptime = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days #Create the new event source if (!(Get-Eventlog -LogName $eventLog -Source $eventSource)){ New-EventLog -LogName $eventLog -Source $eventSource } #Run the restart If($hour -lt 12 -or $hour -gt 16){ Write-Eventlog -LogName $eventLog -Source $eventSource -EntryType $eventType -EventID $eventID -Message "Will not reboot, outside of maintenance hours" } ElseIf($day -ne $rebootDay) { Write-Eventlog -LogName $eventLog -Source $eventSource -EntryType $eventType -EventID $eventID -Message "Will not reboot, outside of maintenance day" } ElseIf($uptime -lt $rebootAge) { Write-Eventlog -LogName $eventLog -Source $eventSource -EntryType $eventType -EventID $eventID -Message "Will not reboot, rebooted within 24 hours" } Else{ (Write-Eventlog -LogName $eventLog -Source $eventSource -EntryType $eventType -EventID $eventID -Message "This system will be restarted by the SafeRestart Powershell Script") (restart-computer -force) }
*This script is “as is” with no warranties. Test it before you trust it!