Hello Everyone,
I have a script that works on some systems but not others, it seems.
It scans a log file and if it finds the key phrase it will email. This job is run by task scheduler on the hour.
Now what’s happening is that it’s sending out this email every hour.
I thought I created a foolproof plan but perhaps not?
Let me know your thoughts.
Dates take this form: [2017-09-28 13:24:59,405]
function Get-CertErr {
$reviewer = Get-WmiObject win32_groupuser |
Where-Object { $_.GroupComponent -match 'user' } |
ForEach-Object {[wmi]$_.PartComponent } |
Where-Object {$_.Name -notmatch '.*test.*|to_be_default|.*User.*|INTERACTIVE'} |
ForEach-Object { $_.Name }
$logs = Get-ChildItem -Path "C:\pathtolog\important.log*" | Where-Object { $_.LastWriteTime -ge ((Get-Date).AddDays(-40))}
$var = Get-Content $logs -EA Ignore | Select-String -SimpleMatch "certificate" -Context 0,10 | Sort-Object Date | Select-Object -Last 1
foreach ($v in $var){
$date,$message = $v.Line.Split("]",2)
$date = $date -replace ('\[','')
$alert1 = "$([datetime]::ParseExact($date,"yyyy-MM-dd HH:mm:ss,fff",$null))"
$alert2 = "$message"
$alert3 = "$v"
}
if ($v){
if(!(Test-Path "C:\Users\Administrator\Desktop\Monitoring")){
New-Item -ItemType directory -Path "C:\Users\Administrator\Desktop\Monitoring"
}
if(!(Test-Path "C:\Users\Administrator\Desktop\Monitoring\Cert.txt")){
New-Item -ItemType file -Path "C:\Users\Administrator\Desktop\Monitoring\Cert.txt"
}
$oc = Get-ChildItem C:\Users\Administrator\Desktop\Monitoring\Cert.txt
$oldcerts = Get-Content $oc | Sort-Object Date | Select-Object -Last 1
if ($date -gt $oldcerts){
Send-Email -To "thatonegroup@Contoso.com" -From "$reviewer@$env:COMPUTERNAME" -Subject "Certificate FAILURE on $reviewer@$env:COMPUTERNAME" -Body $MessageBody -Priority Normal -SMTPServer "relay.contoso.com"
}
}
}
Function Send-Email ($To, $Cc, $Bcc, $From, $Subject, $Body, $Priority, $SMTPServer, $Attachments){
$HTML = @"
body {background-color: lightblue;}
h1 {background-color: black;color: white;text-align: center;}
h2 {background-color:lightGrey;}
p {font-family: verdana;font-size: 12px;}
p.ridge {border-style: ridge;}
Certificate Failure
Failure Date: $(Get-date $alert1 -Format F)
$($alert3|Out-String)
Reviewer: $reviewer
Workstation: $env:COMPUTERNAME
"@
$EmailParams = @{
To = $To
Cc = $Cc
Bcc = $Bcc
From = $From
Subject = $Subject
Body = $HTML
BodyAsHtml = $True
Priority = $Priority
SMTPServer = $SMTPServer
Attachments = $Attachments
ErrorAction = 'Stop'
}
$list = New-Object System.Collections.ArrayList
foreach ($h in $EmailParams.Keys) {
if ($($EmailParams.Item($h)) -eq $null) {
$null = $list.Add($h)
}
}
foreach ($h in $list) {
$EmailParams.Remove($h)
}
Try {
Send-MailMessage @EmailParams;
Write-Verbose "Send-Mail: Sending mail to: $To";
If ($? -eq $true){
$date | Out-File -FilePath "C:\Users\Administrator\Desktop\Monitoring\Cert.txt" -Append -NoClobber -Force
}
}
Catch {
"Failed to send email to $($To) due to: $_"
}
}
Get-CertErr