我正在尝试编写一个powershell命令来搜索包含用户输入的BOTH字符串的文件。现在我可以搜索一个字符串,但无法弄清楚如何确保它有两个字符串。任何帮助将不胜感激。
我在一个存储一堆.SQL文件的本地目录中搜索。文件路径由用户输入(C:\ Program Files \ Common Files),然后第一个字符串由用户输入,最后一个字符串。我需要脚本来搜索所有文件,只显示文档中包含两个字符串的文件。
#Requests the loctation of the files to search
$Location = Read-Host 'What is the folder location of the files you want to search?'
#Sets the location based off of the above variable
Set-Location $Location
#Sets the alias
Set-Alias ss Select-String
#Requests the text to search for in the files
$File_Name = Read-Host 'Object Name?'
$File_Name2 = Read-Host 'Second Object Name'
#Searches the files and returns the filenames
Get-ChildItem -r | Where {!$_.PSIsContainer} | ss -Pattern '($File_Name|$File_Name2)' | Format-List FileName
答案 0 :(得分:5)
或许更简单的方法是只使用Select-String
两次:
$filename1 = [regex]::escape($File_Name)
$filename2 = [regex]::escape($File_Name2)
Get-ChildItem -r | Where {!$_.PSIsContainer} | Select-String $filename1 |
Select-String $filename2
答案 1 :(得分:4)
这对你有用。查看在线评论。
# 1. Let's assume the folder c:\test contains a bunch of plain text files
# and we want to find only the ones containing 'foo' AND 'bar'
$ItemList = Get-ChildItem -Path c:\test -Filter *.txt -Recurse;
# 2. Define the search terms
$Search1 = 'foo';
$Search2 = 'bar';
# 3. For each item returned in step 1, check to see if it matches both strings
foreach ($Item in $ItemList) {
$Content = $null = Get-Content -Path $Item.FullName -Raw;
if ($Content -match $Search1 -and $Content -match $Search2) {
Write-Host -Object ('File ({0}) matched both search terms' -f $Item.FullName);
}
}
创建多个测试文件后,我的输出如下所示:
File (C:\test\test1.txt) matched both search terms
答案 2 :(得分:2)
Trevor Sullivan的解决方案对我来说很好,但是如果你想要一个纯正则表达式的方法,你可以使用以下字符串:
string1(?=string2)|string2(?=string1)
基本上说,
尝试在某处找到string1和string2,
否则尝试在某处找到string2和string1。
您需要逐行搜索整个文件,而不是逐行搜索。