How do I properly use Try/Catch in my PowerShell script to handle event log queries?

0
5
Asked By CuriousCat42 On

Hi everyone! I'm pretty new to scripting and I'm currently working on a PowerShell script that queries an event log for specific IDs within the last 24 hours. My goal is to output the found events into a text file. However, if there are no events found, I'd like to instead write a message saying "No logs to report" to a different text file. The issue I'm facing is that whether or not events are found, I end up with a blank text file and the message gets printed regardless of the event result. Here's a snippet of my script:
```
$startDate = (Get-Date).AddDays(-1)
try {
Get-WinEvent -ComputerName -Credential
-FilterHashtable @{
LogName = "Microsoft-Windows-Dhcp-Server/FilterNotifications"
Id = 20097, 20100
StartTime = $startDate} -ErrorAction Stop | Format-Table -AutoSize -Wrap | Out-File -FilePath C:scriptsdhcplog.txt
}
catch [Exception] {
if ($_.FullyQualifiedErrorId -match "NoMatchingEventsFound") {
Write-Output "No DHCP Filter logs to report in the last 24 hours." >> C:scriptsnothingtoreport.txt
}
}
```
I apologize for the messy formatting, and I really appreciate any help you can give me!

3 Answers

Answered By ScriptGuru On

Just to add on, you mentioned the `nothingtoreport.txt` file ends up being generated regardless, right? It sounds like you may need to focus on correctly managing the output based on the event count. Here’s a slightly modified method that might work better:
First, collect your `Get-WinEvent` output in a variable and only write to `nothingtoreport.txt` if the `$Events` variable is empty after the entire query. This will help you avoid unintended output when events are present. Remember, managing your output files effectively can save you a headache later!

Answered By CodeWhiz187 On

It looks like you might be having some trouble with your script. In your catch block, it seems like the `Write-Output` with the redirect is executed even when you do find events, which is causing the blank file. Instead, try saving the output of `Get-WinEvent` to a variable first, then check if there's any output before deciding what to write to the files. Here's an adjusted version of your code:
```
$startDate = (Get-Date).AddDays(-1)
try {
$Events = Get-WinEvent -ComputerName -Credential -FilterHashtable @{
LogName = "Microsoft-Windows-Dhcp-Server/FilterNotifications"
Id = 20097, 20100
StartTime = $startDate
} -ErrorAction Stop
if ($Events) {
$Events | Out-File -FilePath C:scriptsdhcplog.txt
} else {
"No DHCP Filter logs to report in the last 24 hours." | Out-File C:scriptsnothingtoreport.txt
}
} catch [Exception] {
# Handle other exceptions here if necessary
}
```
This way, you'll only write to `dhcplog.txt` if events are found.

Answered By SmartScripter99 On

One other thing to keep in mind is to avoid using `Format-*` cmdlets when directing output to files. They change the object type, which can lead to unexpected results. If you just want to write the events to a file, piping the `$Events` variable directly to `Out-File` works best. If there are no matching events, ensure your condition correctly identifies it during the catch block. Also, if your scripts run frequently, consider cleaning up the output files before each run to avoid confusion over old data. Typically, the basic structure you have should work if adjusted correctly!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.