Search code examples
windowspowershellscriptingpowershell-2.0powershell-3.0

When trying to kill some particular service through PowerShell, if I found the word @LM_CRITICAL[5310] in txt file. But its not working


I have to kill Processservice.exe service through powershell code, If I found the particular word "@LM_CRITICAL[5310]" in txt log file. I am not getting any error and its not working as expected.

Guess something wrong with matching pattern via -eq or -match or other operators. Also I am suspecting the way I have added the $(Get-TimeStamp) in the output file is the right way. Kinldy correct my mistake.

I need your guidance to fix it. I have attached my powershell code.

I am looking forward to hear from you

function Get-TimeStamp {    
    return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)    
}
$content = get-content S:\logs\processservice\processservice.log.txt
if ( $content -eq "@LM_CRITICAL[5310]")
{
     write-output "$(Get-TimeStamp) Found @LM_CRITICAL[5310] Killing the Processservice task" | Out-file C:\temp\outlog.txt -append
     taskkill /im Processservice.exe /f
}
else
{
    Write-output "$(Get-TimeStamp) @LM_CRITICAL[5310] error code not found in processservice.log.txt" | Out-file C:\temp\outlog.txt -append
}

Solution

  • The -eq operator only works on exact matches, meaning that if a line from your file contains the substring @LM_CRITICAL[5310] AND some other text, it won't work.

    You can use the -match regex operator, just make sure to escape the input pattern with [regex]::Escape():

    if ( $content -match [regex]::Escape("@LM_CRITICAL[5310]") )
    {
        # ... substring was found in at least 1 line
    }