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?
It depends on what you’d like to do. You could add -ErrorAction SilentlyContinue to the command, which will suppress the error. You could then check and see if $UnexpectedReboot was empty or not. That’ll probably be difficult to do in a one-liner; this would be easier for you if you broke these commands out into a short script.
An alternative would be to add -ErrorAction Stop to your Get-EventLog call and enclose the scriptlet in a Try/Catch block. Since you want to ignore the case where no unexpected reboot occurred, the catch block can be empty.
Thank you, Don and Art. I tried Stop first since it was the shorter solution and I believe in KISS. But it still returned an error. I don’t like errors even if they don’t affect he result. SilentlyContinue did not return a error. I solved the problem of $UnexpectedReboot being empty with an If statement. Here is my solution:
The second option will always return true if the variable has a value other than false. Â If it’s empty then it won’t go through.
The other thing is are you sure that you’re getting the right event log information? Â it might be better to look for a particular event ID. Â Right now you’re just pulling any error in the system log that happened within the hour before the script was run.