如何在 Powershell 中搜索文件中的内容

How to search content in files in Powershell

我想制作一个动态函数,在输入的文件中搜索请求的 $ErrorCode,并最终将有错误的文件复制到另一个文件夹。

现在,我的代码只需要一个文件和 return 找到 $Error_Code 的地方的句子。我想搜索多个文件和 return 具有 $ErrorCode 的文件的名称。

function SearchError{

    Param (
        [Parameter (Mandatory=$true)] [STRING] $SourcePath,
        [Parameter (Mandatory=$true)] [STRING] $SourceFile,
        [Parameter (Mandatory=$true)] [STRING] $ErrorCode,
        [Parameter (Mandatory=$true)] [STRING] $FileType
       # [Parameter (Mandatory=$true)] [STRING] $DestPath


        )  
    $TargetPath = "$($SourcePath)$($SourceFile)"
    #Return $TargetPath

    $DestinationPath = "$($DestPath)"
    #Return $DestinationPath 


    #foreach($error in $TargetPath) {

    Get-ChildItem $TargetPath | Select-String -pattern $ErrorCode 

}
SearchError 
  • Select-String 的输出对象 - 类型为 [Microsoft.PowerShell.Commands.MatchInfo] - 具有反映输入文件路径的 .Path 属性。

  • -List 开关添加到 Select-String 使其在文件中的第一个匹配项后停止搜索,因此您将为每个文件准确获得一个输出对象,其中至少找到了 1 个匹配项。

因此,以下仅输出至少找到 1 个匹配项的输入文件的路径:

Get-ChildItem $TargetPath |
  Select-String -List -Pattern $ErrorCode | ForEach-Object Path

注意:-Pattern 支持 数组 正则表达式模式,因此如果您将 $ErrorCode 参数定义为 [string[]],具有任何一个 模式都会匹配;使用 -SimpleMatch 而不是 -Pattern 来搜索 文字子串


回复:

eventually copy the files with the error to another folder

只需将 | Copy-Item -Destination $DestPath 附加到上述命令即可。

回复:

I want to search through multiple files

根据您的需要,您可以使您的 $SourcePath$SourceFile 参数 array-valued ([string[]]) 和/或传递通配符表达式作为参数。