我正在尝试搜索文件中的字符串并显示包含字符串的文件名
我写了一个如下的脚本。
Function GetFileContainsData ([string] $Folderpath,[string] $filename, [string] $Data) {
$Files=Get-ChildItem $Folderpath -include $filename -recurse | Select-String -pattern $Data | group path | select name
return,$Files
}
$configFiles= GetFileContainsData "C:\MyApplication" "web.config" "localhost"
Foreach ($file in $configFiles) { Add-Content -Path "Filelist.txt" -Value $file.Name}
此脚本将包含字符串“localhost”的所有文件名写入Filelist.txt。
我想找到多个字符串。如果我传递一个数组
$stringstofind=("localhost","$env:ComputerName")
Foreach ($strings in $stringsToFind) {
$configFiles= GetFileContainsData $Installpath "web.config" $strings
Foreach ($file in $configFiles) { Add-Content -Path "Filelist.txt" -Value $file.Name}
}
它将在数组中查找包含文件列表的每个字符串并进行更新。如果同一个文件同时包含两个字符串,则它将在Filelist.txt中包含该文件的2个条目。
是否可以在文件中找到多个字符串并列出文件名? [这样可以消除文件名的冗余输入]
答案 0 :(得分:2)
实际上,Select-String
接受string[]
作为-Pattern
的参数,因此您不需要循环。
然后,您可以使用Get-Unique
删除重复项。
事实上,Select-String
也接受一个文件列表作为路径,所以你可以这样做:
Get-ChildItem $FolderPath -Include $Filenames -Recurse | Select-String -Pattern $StringsToFind | Select-Object path | Sort-Object | Get-Unique -AsString
在一行中替换函数和循环
编辑:最终的工作版本是
$Files=Get-ChildItem $Folderpath -include $filename -recurse | Select-String -pattern $Data | group path | select name |Get-Unique -AsString
答案 1 :(得分:0)
以下脚本将解决我遇到的问题。感谢carlpett的有用输入
<#
.NAME
Get-FilenameHasString
.SYNOPSIS
To search strings in file and return the filenames.
.DESCRIPTION
This script will be useful to find strings in list of files.
It will eliminate the duplicate filenames
.PARAMETER Filenames
This parameter will be having filenames where the string needs to be searched.
.PARAMETER FolderPath
This parameter will be having folder where it will look for the filenames
.PARAMETER StringsToFind
This parameter will be having the strings to be searched
.EXAMPLE
.\Get-FilenameHasString -Filenames "Web.config" -FolderPath "C:\Program Files (x86)\MyProj" -$StringsToFind ("$env:ComputerName","localhost")
To get the list of web.config files which is there in Folder path having StringsTofind. The result will be saved in Filelist.log by default.
#>
Param (
$Filenames="web.config",
$FolderPath="C:\Program Files (x86)\MyProj",
$StringsToFind=("$env:ComputerName","localhost"),
$Logfile="FileList.log"
)
$configFiles= Get-ChildItem $FolderPath -Include $Filenames -Recurse | Select-String -Pattern $StringsToFind | Group path | select name | Get-Unique -AsString
Foreach ($file in $configFiles) { Add-Content -Path $Logfile -Value $file.Name}