I’ve written this PowerShell script to search for specific txt in recent logfiles (changed within last 24 hours). The output is returned to standard out.
# *****************************************************************************
# Scriptnaam: CHECKLOGFILES.PS1
# Written_by: Tim van Kooten Niekerk
# Versie: 20120522B
# Info: PowerShell script to search for specific text in files modified in the last 24 hours.
# *****************************************************************************
# Functions en Procedures...
function fGetFileModTime([string]$sFileName) {
$vFileInfo = get-childitem $sFileName
return $vFileInfo.lastwritetime
}
function fSendMessage([string]$sNode, [string]$sApplication, [string]$sMessage) {
$sMessage
# And send result to operations...
#return Start-Process...
}
# Start Main script...
if (($args[0]) -and ($args[1]) -and ($args[2]) -and ($args[3])) {
# Check if path exists...
if (Test-Path $args[0]) {
# Check for searchterm in files modified in the last 24 hours...
[boolean]$bResultFound = $false
[string]$sSearchTerm = $args[1]
Get-ChildItem $($args[0]) | where {$_.LastWriteTime -gt (Get-Date).AddHours(-24)} |
% {
$oResult1 = select-string -path $_.fullname -pattern $sSearchTerm -context 0
if (($oResult1.Linenumber -gt 0) -or ($oResult1.Count -gt 0)) {
$sResult1 = $oResult1 | format-list -property line,path,linenumber | Out-String
[string]$sResultMerge = [string]$sResultMerge + $sResult1
$bResultFound = $true
}
}
# $sResult1 = select-string -path $($args[0]) -pattern $($args[1]) -context 0
# Send message when searchterm is found...
if ($bResultFound -eq $true) {
$sMessage1 = "Searchterm [" + $args[1] + "] found in recent logfiles... `r`n`r`nRESULT:"
fSendMessage $args[2] $args[3] $sMessage1
}
} else {
$sMessage1 = "Error executing ... `r`n`r`nERROR: Pad niet gevonden."
fSendMessage $args[2] $args[3] $sMessage1
}
} else {
"Error executing script... `r`n`r`nERROR: Arguments missing."
"SYNTAX: checklogfiles.ps1 `"<c:pathtodir*.log>`" `"<searchterm>`" `"<hostname>`" `"<service>`""
}