我有個問題。我將在我的計算機上搜索檔案以查找檔案中的關鍵字。例如,關鍵字是“C:\Project”。在下面運行此腳本時出現錯誤。但是當我在搜索字串中洗掉 C:\ 時,它正在作業。但我有興趣在開始時使用 C:\ 進行搜索。有人可以幫我更正腳本嗎?
$path = 'D:\Cross'
$searchword = 'C:\Project'
$Filename = '*.config'
Get-ChildItem $path -Include "$Filename" -Recurse | ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $searchword ){
$PathArray = $_.FullName
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
uj5u.com熱心網友回復:
Select-String默認為正則運算式,因此如果您想要一個簡單的子字串搜索,請使用-SimpleMatch開關:
Get-Content $_.FullName | Select-String -Pattern $searchword -SimpleMatch
或確保您轉義任何正則運算式元字符:
Get-Content $_.FullName | Select-String -Pattern $([regex]::Escape($searchword))
您還可以通過Where-Object直接使用檔案物件并將其通過管道傳輸到Select-String而不是手動呼叫來顯著簡化代碼Get-Content:
$filesWithKeyword = Get-ChildItem $path -Include "$Filename" -Recurse |Where-Object { $_ |Select-String -Pattern $searchword -SimpleMatch |Select-Object -First 1 }
$filesWithKeyword現在包含在磁盤上的相應檔案中找到至少 1 次關鍵字出現的所有FileInfo物件Select-String。Select-Object -First 1確保管道在發現第一次出現時立即中止,從而避免一直讀取大檔案的需求。
整個腳本就變成了:
$path = 'D:\Cross'
$searchword = 'C:\Project'
$Filename = '*.config'
$filesWithKeyword = Get-ChildItem $path -Include "$Filename" -Recurse |Where-Object { $_ |Select-String -Pattern $searchword -SimpleMatch |Select-Object -First 1 }
Write-Host "Contents of ArrayPath:"
$filesWithKeyword.FullName
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327027.html
