Rob Wiley
Rob Wiley

Reputation: 85

Powershell switch regex fails when run from script but succeeds in console

This is running in Powershell v2 on a Windows XP SP3 in a powershell -noprofile.

The Powershell script below works if I copy and paste it into the console but does not work if I run it as a script. Can anyone see what might be causing that?

The script is as follows (some names have been changed to protect the innocent).

#Known Error values to count instances of
$KnownErrorText = @"
Invalid Descriptor Index
Syntax error or access violation
An error occurred while attemping to update a record
Message from LDAP server: Invalid credentials
Error sending data over TCP connection
"@

#Fix the variable so it's an array
$KnownErrorText = $knownErrorText.split("`n")

#output variables
$KnownErrors = @{}
$UnknownErrors = @()

#Generate the hash to contain counts of the the known errors
foreach ($line in $knownErrorText) {$KnownErrors.Add($line,0)}

#Get error lines from the log
$scerrors = Select-String -Path "\\myserver01\d$\logs\application.log" -Pattern "Error"

"$($scerrors.count) errors to process"
$ProcessedErrors = 1

#Look at each error.  Pass the error through a switch to identify whether it's
#a known error or not. If it's Known, increment the appropriate count in the hash
#if it's not known, add it to the unknown errors output variable
foreach ($e in $scerrors) {
    "$($ProcessedErrors)`tProcessing`t$($e.line)"
    $addToUnknown = $true
    "e.line type:`t$($e.line.gettype().name)`tLength$($e.line.length)"
    switch -regex ($knownErrorText) {
             #Look in the text of the current error for the any of the errors in
             #the KnownErrorText array
             #THIS IS THE PART THAT DOESN'T WORK WHEN RUNNING IN A SCRIPT
     {"$($e.line)" -match "^.*$($_).*`$"} {
        Write-host "Matched $($_)" -ForegroundColor Green -BackgroundColor Black
        $KnownErrors.Set_Item($_,([int]$KnownErrors.Get_Item($_))+1)
        $addToUnknown = $false
                    #We found our match so stop 
                    #processing the KnownErrorText array through the switch
        break
     }
     default {
        Write-host "UnMatched`t$($_)" -ForegroundColor Red -BackgroundColor Black
     }
 }

     #If we got through all the KnownErrorText values without finding a match, 
     #add the error to the UnknownErrors array to be displayed
 if ($addToUnknown) {$UnknownErrors += $e}

 $ProcessedErrors++
 if ($ProcessedErrors -ge 5) {break}
 }

#Console reporting
"Known Errors:"
$KnownErrors.GetEnumerator() | Sort-Object Value -Descending
""
"$($UnknownErrors.count) Unknown Errors:"
$UnknownErrors | Foreach {$_.line}

When I run this as a script (for example if saved to c:\temp\ErrorReporting.ps1 and called with & c:\Temp\ErrorReporting.ps1

the match portion fails:

{"$($e.line)" -match "^.*$($_).*$"}`

Upvotes: 0

Views: 1161

Answers (1)

latkin
latkin

Reputation: 16792

The issue is due to the string split operation working differently in script vs in the console. Pasting into the console might produce different line endings that a saved script file contains (\r\n vs just \n). So it would help to specify the $knownErrorText array explicitly rather than splitting a string to produce it.

$knownErrorText = 'Invalid Descriptor Index',
                  'Syntax error or access violation',
                  ...

Aside:

You are not using switch -Regex as intended. The standard usage is not to have a scriptblock which is doing a -match comparison to define the cases, but to simply provide a regex string which the input is matched against. For example

$myStr = 'abc123'
switch -regex ($myStr)
{
   'abc\d\d\d' { 'abc with 3 numbers'; break }
   'xyz\d\d\d' { 'xyz with 3 numbers'; break }
}

If you are doing checks inside of scriptblocks to define the cases, you actually don't need the -regex flag at all.

Your goal seems to be to check if $e.Line contains any of the known error messages. If so, then a switch probably isn't the best tool, anyways. You can do this very simply like below:

foreach ($e in $scerrors)
{
   if( $knownErrors |?{$e.Line -match $_} )
   {
      "$($e.Line) matches a known error"
   }
   else
   {
      "$($e.Line) does not match a known error"
   }
}

Upvotes: 1

Related Questions