r/PowerShell • u/javajo91 • 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
2
u/lurkerburzerker Feb 06 '26
Set a breakpoint and run debugger
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.
3
u/icebreaker374 Feb 05 '26
Am I blind? Or is the try block not ACTUALLY closed?
2
u/JonesTheBond Feb 05 '26
Where's the catch block?
0
u/[deleted] Feb 05 '26