Reading "exit code [0]" from a log file in powershell

Durgesh007 1 Reputation point
2020-07-28T12:24:51.077+00:00

When an installation is successful the last line in the log file shows "exit code [0]" . I want to read that line using my script and get the result. I am able to read just the string "exit code" but its not able to read "[0]". Can someone pls suggest me how to read the whole thing "exit code [0]" as string

if ($textcode -imatch "exit code [0]")
{
Write-Host "Success"
}
else
{
Write-Host "Not Success"
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,455 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,831 Reputation points
    2020-07-28T15:14:36.327+00:00

    The characters "[" and "]" together are used to denote a character class in regular expressions. The effect is that you're trying to match "exit code 0".

    Alter your regex by escaping either the first, or both, of the "[" and "]" characters.

    Here's an example:

    'exit code [0]','exit code 0' |
        ForEach-Object{
            if ($_ -match 'exit code [0]'){Write-Host "'exit code [0]' matched '$_'"}
            if ($_ -match 'exit code \[0]'){Write "'exit code \[0]' matched '$_'"}
    #        if ($_ -match 'exit code [0\]'){Write "'exit code [0\]' matched '$_'"}    ## THIS WILL FAIL!!!!
            if ($_ -match 'exit code \[0\]'){Write "'exit code \[0\]' matched '$_'"}
        }
    

    If you escape only the "]" you'll get an error for having an "unterminated [] set"

    2 people found this answer helpful.
    0 comments No comments