我想在递归子文件夹的文件的文件夹中搜索某个字符串(例如“Banana”)。我似乎无法让它工作......

这是我得到的:

$Searchstring='Banana' 
$PathArray=@() 
$Path='C:\users\myuser' 
$content= Get-Content $_.FullName  
 
 Get-ChildItem $Path |  
  Where-Object { $_.Attributes -ne "Directory"} 
 
      ForEach-Object (  
         If ($content | Select-String -Pattern $Searchstring) { 
           $PathArray += $_.FullName 
 
         } 
      ) 

不幸的是,这个脚本不符合我的要求。

请您参考如下方法:

这是一个非常简单的解决方案:

$SearchInDirectory = "C:\SearchingFolder"; 
$SearchForString = "Banana"; #String for searching 
$SearchInFormats = "*.asp", "*.txt", "*.js"; #If empty will search in all file formats 
 
echo 'Searching in progress...' 
Get-ChildItem  $SearchInDirectory  -include $SearchInFormats   -recurse  |  Select-String  -pattern  $SearchForString  -SimpleMatch  |  group path  |  select name 

它在所有目录和子目录中(递归地)搜索所有结果,然后打印它们,因此如果您有很多文件和目录,可能需要一些时间。此外,您可以指定需要检查的文件类型(但不一定)。

此外,我还有一个脚本可以将结果放入文件中:

$SearchInDirectory = "C:\SearchingFolder"; 
$SearchForString = "Banana"; #String for searching 
$SearchInFormats = "*.asp", "*.txt", "*.js"; #You can specify the file types 
$PutSearchResultsInFile = ""; #link to a file or if blank - the results to be displayed on screen 
 
Cls; 
 
function SearchFilesByString_results () { 
    Get-ChildItem  $SearchInDirectory  -include $SearchInFormats   -recurse  |  Select-String  -pattern  $SearchForString  -SimpleMatch  |  group path  |  select name 
} 
 
if($PutSearchResultsInFile){ 
        if(!(Test-Path -Path $PutSearchResultsInFile)){ 
           New-Item $PutSearchResultsInFile -itemType "file" -confirm:$false | Out-Null  
           echo "`nNew file created. `n"; 
        }  
        echo "Searching in progress... `n"; 
        SearchFilesByString_results > $PutSearchResultsInFile; 
        echo "Search completed! Find results here: " $PutSearchResultsInFile "`n"; 
} else { 
    echo "`nSearching in progress.... `n"; 
    SearchFilesByString_results 
    echo "`nSearch completed! `n"; 
} 

希望对您有所帮助! :)


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!