Home > Net >  Powershell find string in log file
Powershell find string in log file

Time:11-19

I'm completely new to Powershell and trying to accomplish a small task. I'm trying to find a string in the last two lines of a log file, and if the value doesn't match, take and action. If it matches, end. I think that's the simplest way to explain it. :-) I'm searching for certain words, if not found, open notepad, if found, exit. I've pieced some of it together, but I'm not sure how to handle the If False, run notepad portion. Would love some help. Thanks.

if (Test-Path C:\windows\ccm\logs\CcmEval.log) {

Get-Content 'C:\windows\ccm\logs\CcmEval.log' -Tail 2 | Select-String "Updating MDM_ConfigSetting.ClientHealthStatus with value 7" | % { $_ -notmatch "value 7" }

   Start-Process C:\windows\notepad.exe 
    
    }

CodePudding user response:

You can do that with that with one more if else condition. If condition not matches it will open notepad otherwise it will execute your command to exit.

if (Test-Path C:\windows\ccm\logs\CcmEval.log) {
    $condition = Get-Content 'C:\windows\ccm\logs\CcmEval.log' -Tail 2 | Select-String "Updating MDM_ConfigSetting.ClientHealthStatus with value 7" | % { $_ -notmatch "value 7" }
    if (!$condition) {
        Start-Process C:\windows\notepad.exe
    }
    else {
          "Do something here"
    }
        
}

CodePudding user response:

You can drop the Test-Path if you add -ErrorAction SilentlyContinue to the Get-Content, so it will quietly return nothing if the file is not found. This means you can use the same code whether or not the file exists.

-match takes a regular expression pattern, which is powerful enough that you can build "not 7" into it in one go using [^7] to mean "any character except 7".

$logFile = 'C:\windows\ccm\logs\CcmEval.log'
$lines = Get-Content -Path $logFile -Tail 2 -ErrorAction SilentlyContinue

if ($lines -match "Updating MDM_ConfigSetting.ClientHealthStatus with value [^7]") {

   Start-Process C:\windows\notepad.exe 
    
}
  • Related