r/PowerShell • • Feb 05 '26

Question Need help with Try / Catch script.

Good afternoon!

Noob here.

I'm trying to write a script that will query an event log for certain IDs for the last 24 hrs.

If it finds events, id like to print to a text file.

If It does not find any events, I'd like to print a different message saying "No logs to report" and print that instead. However, currently my issue is that if there are no events, the script prints out a blank text file AND prints the message "No logs to report"

Here is what I have so far:

$startDate = (Get-Date).AddDays(-1)
try {
    Get-WinEvent -ComputerName <server1> -Credential <username> 
    -FilterHashtable @{
    LogName = "Microsoft-Windows-Dhcp-Server/FilterNotifications"
    Id = 20097, 20100
    StartTime = $startDate} -ErrorAction Stop | Format-Table -AutoSize 
    - Wrap | Out-File -FilePath C:\scripts\dhcplog.txt 
    }
catch [Exception] {
    if ($_.FullyQualifiedErrorId -match "NoMatchingEventsFound") {
    Write-Output "No DHCP Filter logs to report in the last 24 hours." 
    >> C:\scripts\nothingtoreport.txt
    }
    }

My apologies for the code formatting.

Thank you!

3 Upvotes

9 comments sorted by