我正在嘗試使用以下命令在目錄中搜索特定檔案:
gci -recurse -path "E:\" | select-string "searchContent" | select path
這樣做給了我一個記憶體不足錯誤。我已經看到其他帖子建議將其管道化到 foreach-object,但我不知道如何讓它在我的場景中作業。任何幫助表示贊賞!
uj5u.com熱心網友回復:
將檔案作為一個整體(單個多行字串)讀取時,您的搜索速度比逐行測驗要快得多。
此外,如果您可以使用檔案名模式作為Get-ChildItemcmdlet 的過濾器,則可以顯著加快速度。例如,如果您只想搜索.txt檔案,請添加-Filter '*.txt'.
在任何情況下,附加開關-File以便 Get-ChildItem 不會嘗試將 DirectoryInfo 物件傳遞給代碼的其余部分。
嘗試:
# since we use regular expression operator `-match`, escape the word or phrase you need to find
$searchContent = [regex]::Escape('whateveryouarelookingfor')
$result = Get-ChildItem -Path 'E:\' -Recurse -File | ForEach-Object {
if ((Get-Content -Path $_.FullName -Raw) -match $searchContent) { $_.FullName }
}
比 using 快一點ForEach-Object{..}是使用 aforeach()代替(跳過管道結果所需的處理時間)
# since we use regular expression operator `-match`, escape the word or phrase you need to find
$searchContent = [regex]::Escape('whateveryouarelookingfor')
$result = foreach ($file in (Get-ChildItem -Path 'E:\' -Recurse -File)) {
if ((Get-Content -Path $file.FullName -Raw) -match $searchContent) { $file.FullName }
}
現在您可以在螢屏上顯示完整路徑和檔案名
$result
并將其保存為磁盤上的文本檔案
$result | Set-Content -Path ('X:\FilesContaining_{0}.txt' -f $searchContent)
uj5u.com熱心網友回復:
只需將它分配給一個變數,然后有一個 foreach 回圈,將每個回圈分配給另一個變數。
$files = gci -recurse -path "E:\"
foreach ($fileName in $files)
{
if ($fileName.Name -like "*searchContent*")
{
write-host $fileName.Name
}
}
uj5u.com熱心網友回復:
我覺得這應該消耗更少的記憶體。不能確定,但??你可以告訴我。概念相同,但使用[System.IO.StreamReader].
注意:這將繼續查找它可以找到的所有檔案,如果您需要回圈在第一次查找時停止,則應添加新條件。
foreach($file in Get-ChildItem -Recurse -path "E:\" -File)
{
$reader = [System.IO.StreamReader]::new($file.FullName)
while(-not $reader.EndOfStream)
{
if($reader.ReadLine() -match 'searchContent')
{
$file.FullName
break
}
}
$reader.Dispose()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366210.html
標籤:电源外壳
