所以我有一個管道,它將搜索特定流的檔案,如果找到將用掩碼值替換它,我試圖在 oldValue 被 newValue 替換的所有時間都有一個計數器。它不一定需要是單班輪,只是好奇你們會怎么做。蒂亞!
Get-Content -Path $filePath |
ForEach-Object {
$_ -replace "$oldValue", "$newValue"
} |
Set-Content $filePath
uj5u.com熱心網友回復:
我建議:
使用
Get-Content's-Raw開關將整個輸入檔案作為單個字串讀取。將
-replace/[regex]::Replace()與腳本塊一起使用來確定替換文本,這允許您在每次進行替換時增加計數器變數。
注意:由于您要用結果替換輸入檔案,因此請務必先制作備份副本,以確保安全。
在PowerShell (Core) 7 中,-replace運算子現在直接接受允許您動態確定替換文本的腳本塊:
$count = 0
(Get-Content -Raw $filePath) -replace $oldValue, { $newValue; $count } |
Set-Content -NoNewLine $filePath
$count 現在包含執行的所有行(包括同一行上的多個匹配項)的替換次數。
在Windows PowerShell 中,需要直接使用底層 .NET API [regex]::Replace():
$count = 0
[regex]::Replace(
(Get-Content -Raw $filePath),
$oldValue,
{ $newValue; (Get-Variable count).Value }
) | Set-Content -NoNewLine $filePath
請注意需要使用 (Get-Variable count).Value以增加呼叫者范圍內的$count變數。與PowerShell 7 不同,腳本塊在子作用域中運行。-replace
作為旁白:
- 對于這個用例,使用腳本塊的唯一原因是計數器變數可以增加 - 替換文本本身是靜態的。有關示例,請參閱此答案以獲取真正需要動態確定替換文本的示例,方法是從手頭的匹配項中派生,并將其傳遞給腳本塊。
uj5u.com熱心網友回復:
由于評論中的更多說明而更改我的答案。我能想到的最好方法是提前獲取 $Oldvalue 的數量。那就換!
$content = Get-Content -Path $filePath
$toBeReplaced = Select-String -InputObject $content -Pattern $oldValue -AllMatches
$replacedTotal = $toBeReplaced.Matches.Count
$content | ForEach-Object {$_ -replace "$oldValue", "$newValue"} | Set-Content $filePath
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327019.html
標籤:电源外壳
上一篇:PowershellFolderBrowserDialog從shell到ise的行為不同
下一篇:將回傳值存盤到變數
