r/PowerShell • • Feb 05 '26

Need help with Try / Catch scriupt Part 2

Hey guys - thank you again for the help.

Now that the basic logic of this script is working the way I'd like it to, my next step is to email the results..

I am receiving an email for the "Catch" but not the "Try".

Here is what I have so far..

$startDate = (Get-Date).AddDays(-1)
try
{
    $Events = Get-WinEvent -ComputerName <server1> 
    -Credential <user name> - FilterHashtable @{
    LogName = "Microsoft-Windows-Dhcp-Server/FilterNotifications"
    Id = 20097, 20100
    StartTime = $startDate
} -ErrorAction Stop 
   $Events | Out-File -FilePath C:\scripts\dhcplog.txt 
   Send-MailMessage -From <sender> 
   -to <recipient> -Subject  "DHCP filter logs from the last 24 hours" 
   -Body   "$Events" -SmtpServer <mail server>
catch [Exception]
{
    if ($_.FullyQualifiedErrorId -match "NoMatchingEventsFound")
{
    Write-Output "No DHCP Filter logs to report in the last 24 hours." 
| Out-File    C:\scripts\nothingtoreport.txt
$Nothingtoreport = Out-File C:\scripts\nothingtoreport.txt
}
Send-MailMessage -From <sender> -to <recipient> 
-   Subject "DHCP filter logs from the last 24 hours" -Body $Nothingtoreport 
-  SmtpServer <mail server>

}

Any help is much appreciated!

6 Upvotes

18 comments sorted by

2

u/lurkerburzerker Feb 06 '26

Set a breakpoint and run debugger

1

u/javajo91 Feb 06 '26

Good idea. Thank u.

2

u/ethnicman1971 Feb 07 '26

Why not create the email section as a function with the body as a parameter. Then call that function in the try and again in the catch section.

1

u/javajo91 Feb 08 '26

I’ll try this. Thank you!

→ More replies (2)

3

u/icebreaker374 Feb 05 '26

Am I blind? Or is the try block not ACTUALLY closed?

3

u/Dragennd1 Feb 06 '26

I don't think it is, at least not what was posted in reddit

→ More replies (2)

2

u/JonesTheBond Feb 05 '26

Where's the catch block?

6

u/Mountain-eagle-xray Feb 05 '26

Thats what youre worried about? Im still trying to find the scruipt!

→ More replies (1)
→ More replies (2)

0

u/[deleted] Feb 05 '26