查找包含特定字符串的所有文件和行

Nor*_*eld 2 powershell file-search

我对 powershell 很陌生,我需要帮助我的同事在包含单词/Documents/.

输出必须在包含该文件中的路径和行的文本文件中。

首先,我设法使用以下代码提取路径。但我无法包含以下几行:

$path = 'C:\Users\XXX'
$Text =”/Documents/"
$PathArray = @()

Get-ChildItem $path -Filter *.rdl -Recurse |
 ForEach-Object { 
 If (Get-Content $_.FullName | Select-String -Pattern $Text ){
            $PathArray += $_.FullName
            $PathArray += $_.FullName

           #write-Host "jhk"
         }
    $PathArray | % {$_} | Out-File "C:\Users\XX\tes2.txt"-Append
 }
 Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
Run Code Online (Sandbox Code Playgroud)

此代码有效,但如上所述,我不确定如何添加行。

pos*_*ote 6

至关重要的是,如果您是新手,您首先要花时间提升自己,以防止您将遇到的许多不必要的挫折和困惑。

在 PowerShellYouTube上的Microsoft Virtual Academy 上搜索免费视频培训。

以下是一些其他资源和建议:

  • 网站提供免费电子书
  • 阅读您尝试使用的任何 cmdlet 的完整帮助文件
  • 用例子练习
  • 再次阅读帮助文件
  • 挑选几本好书,例如“一个月的午餐中的 PowerShell”
  • Microsoft 的网站和其他网站上有很多免费的 PowerShell 电子书。

另请参阅:PowerShell 生存指南

至于你的问题的具体例子。这种方法怎么样?

$searchWords = @('Hello','Client')

Foreach ($sw in $searchWords)
{
    Get-Childitem -Path "d:\temp" -Recurse -include "*.txt","*.csv" | 
    Select-String -Pattern "$sw" | 
    Select Path,LineNumber,@{n='SearchWord';e={$sw}}
}


# Partial Results

Path                                            LineNumber SearchWord
----                                            ---------- ----------
D:\temp\Duplicates\BeforeRename1\PsGet.txt             157 Hello     
D:\temp\Duplicates\BeforeRename1\PsGet.txt             161 Hello     
D:\temp\Duplicates\BeforeRename1\StringText.txt          1 Hello     
D:\temp\Duplicates\PoSH\PsGet.txt                      157 Hello     
D:\temp\Duplicates\PoSH\PsGet.txt                      161 Hello     
D:\temp\Duplicates\PoSH\StringText.txt                   1 Hello     
...    
D:\temp\Duplicates\BeforeRename1\PoSH-Get-Mo...        108 Client    
D:\temp\Duplicates\BeforeRename1\Powershell ...         12 Client    
D:\temp\Duplicates\BeforeRename1\Powershell ...         15 Client    
... 
D:\temp\Duplicates\BeforeRename1\WindowsFeat...         92 Client    
D:\temp\Duplicates\BeforeRename1\WindowsFeat...         94 Client    
D:\temp\Duplicates\BeforeRename1\WindowsFeat...        149 Client    
D:\temp\Duplicates\BeforeRename1\WindowsFeat...        157 Client    
D:\temp\Duplicates\BeforeRename1\WindowsFeat...        191 Client    
D:\temp\Duplicates\BeforeRename1\WindowsFeat...        239 Client    
D:\temp\Duplicates\BeforeRename1\WindowsFeat...        241 Client  
Run Code Online (Sandbox Code Playgroud)