Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

Powershell custom date and time in search

Newbie PS Question - Revising question as I think I am about 95% to my solution based on community help so far.

My PS script is querying a .log file and if it matches a -15 minute rule as well as a text selection, it pulls all of the records I want. Which is fantastic.

The issue I have is that I need to email the results to me if those conditions are met. As you can see in the code below, i have the mail setup, but when it comes to the body of the email I get no data. I have tried setting Body = $body but it breaks. Any suggestions on how to get this sorted?

Current Code:

$qtime = Get-Date (Get-Date).AddMinutes(-15) -Format 'yyyyMMddHHmm'
$srch = [regex]::Escape('Licensing: no speech license available for the feature')
$SEL = Select-String -Path C:ProgramDataNuanceEnterprisesystemdiagnosticLogs
rs.log -Pattern "Licensing: no speech license available for the feature"
if ($SEL -ne $null)
 $body =  Get-Content C:ProgramDataNuanceEnterprisesystemdiagnosticLogs
rs.log | Where  { $_ -gt $qtime -and $_ -match $srch}
    #    Send-MailMessage -From '[email protected]' -To  '[email protected]' -Subject 'TTS License Error Detected on ServerA' -SmtpServer 'smtp.domain.com' -body $body
    ## Do Nothing

Thanks in advance -


Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try to extract the first 14 characters of each line and parse them as a [datetime] value, but you don't actually need to do that.

Big-endian date formats (like your YYYYMMddHHmmss format for example), are alphabetically ordered - that is, if one date predates another, it will also precede it when sorted alphabetically.

That means we can just use a date/time string of the same format, describing the cutoff date, and then compare the lines from the log file to that:

$since = Get-Date (Get-Date).AddYears(-4) -Format 'YYYYMMdd'

# this will only return the last 4 years worth of logs
Get-Content old.log | Where { $_ -gt $since } 

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share