我正在尝试微调我的脚本,并希望看看我是否可以得到它的帮助。我目前已经编写了脚本来搜索输入目录中的文件,但是它会获取部分搜索术语而不是完全匹配。例子......我正在寻找抢劫,但我的搜索返回了rob,robert和roberta ......我需要确保当我搜索抢劫时,它只会返回抢劫。任何帮助将不胜感激。
#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
#1. Goes thru all the files and subfiles looking for all .sql
$ItemList = Get-ChildItem -Path $Location -Filter *.sql -Recurse;
#2. Define the search parameters
$Search1 = Read-Host 'First Object Name?';
$Search2 = Read-Host 'Second Object Name?';
#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);
}
}
#Sets location back to root
Set-Location C:
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
答案 0 :(得分:5)
对于完全匹配,您需要匹配字边界(\b
):
if ($Content -match "\b$Search1\b" -and $Content -match "\b$Search2\b") {
...
}
有些字符(所谓的元字符)在正则表达式中具有特殊含义,例如: \
,^
或方括号。如果您希望将搜索字词中的所有内容视为文字字符,则应在条件中使用它们之前考虑转义这些字词:
$Search1 = [regex]::Escape($Search1)
$Search2 = [regex]::Escape($Search2)