首页 > 解决方案 > 即使没有匹配,也要匹配

问题描述

我正在尝试在 powershell 中使用 -match 查找字符串“ErrorCode”:1。我发现了许多带有 ErrorCode:1 的文件。问题是,当我打开一个由于匹配表达式而给出的文件进行检查时,我什至没有找到 ErrorCode 这个词,但文件名仍然作为输出提供给我

我试图检查文件,但许多文件都有我正在搜索的字符串,但很多文件没有。

$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
    }
}

这是我作为输出得到的文件内容之一

<!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>

有人可以帮助解释这个文件是如何输出的吗?

标签: powershell

解决方案


从我之前对您的问题的回答中,您已经有了一个可行的解决方案。这里的问题是Get-Content $file | %{$_ -match '"ErrorCode": [1-9]\d*'}返回一个数组(truefalse值),所以if语句总是true.

要么接受我之前的建议,要么接受Mike 的建议


推荐阅读