I am new to powershell and need some help.Â I am creating a script to be runÂ as aÂ scheduled task at startup to look for event log entries of unexpected shutdown.Â I am only interested in the events that occured within the last hour of startup.Â If an event is found, an email is sent to the helpdesk.Â The script I created works if an entry exists but errors if it does not. It fails because nothing is found to assign to the variable. How can I handle that situation?
$UnexpectedReboot=Get-EventLog -LogName System -EntryType Error -Source EventLog -After (Get-Date).AddHours(-1) -Newest 1 Send-MailMessage -To Helpdesk@company.com -From "UnexpectedShutdown@company.com" -SmtpServer mailserver.company.com -Subject "Unexpected shutdown: $env:COMPUTERNAME" -Body $UnexpectedReboot.Message
The error is:
Get-EventLog : No matches found
At line:1 char:19
- $UnexpectedReboot=Get-EventLog -LogName System -EntryType Error -Source EventLog …
- CategoryInfo : ObjectNotFound: ( [Get-EventLog], ArgumentException
- FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand