Getting a match even if there is not one

Viewed 59

I am trying to find the string "ErrorCode":1 using -match in powershell. I found many files with ErrorCode:1. The problem is that when I opened a file given as a result of a match expression to check I did not even find the word ErrorCode and still the filename was given to me as an output

I tried to check files but many file have the string I am searching for but many does not have it.

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.data
$FoldersToRename = @() #initialize as array
foreach ($file in $fileNames) {
    If (Get-Content $file | %{$_ -match '"ErrorCode":1'}) 
    # If (Get-Content $file | %{$_ -match '"ErrorCode": [1-9]\d*'}) 
    {
        $FoldersToRename += Split-Path $file
        echo $file
    }
}

This is one of the file content I got as an output

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>

Can someone help explain how this file got to be in output?

3 Answers

You already have a working solution from my previous answer to your question. The problem here is that Get-Content $file | %{$_ -match '"ErrorCode": [1-9]\d*'} returns an array (of true or false values), so the if statement is always true.

Either go with my previous suggestion, or with Mike's

Try to seperate the Get-Content command.

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.data
$FoldersToRename = @() #initialize as array
foreach ($file in $fileNames) {
    $content = Get-Content $file
    If ($content -match '"ErrorCode":1'}) 
    # If (Get-Content $file | %{$_ -match '"ErrorCode": [1-9]\d*'}) 
    {
        $FoldersToRename += Split-Path $file
        echo $file
    }
}

The problem is the way you have phrased the IF statement will be true if a file has content. A better way to check the contents of a files using a regex would be to use the Select-String, far simpler than all this looping nonsense. Something like this:

$FoldersToRename = (Split-Path (Get-ChildItem -Path $scriptPath -Recurse -Include *.data | Select-String -pattern '"ErrorCode":1').Path) | Select -unique
Related