簡體   English   中英

Powershell 查找和替換腳本

[英]Powershell Find and Replace Script

模式匹配正在返回 $True 所以我認為測試應該繼續運行替換,而是只是處於無響應模式。 我的測試有什么問題沒有將最后 3 行替換為“NOW in the PRIMARY or SECONDARY role”

service.log 文件具有以下語法行:

NOW in the PRIMARY or SECONDARY role
End of Job Run
NOW in the PRIMARY or SECONDARY role
End of Job Run
NOW in the PRIMARY or SECONDARY role
End of Job Run
NOW in the PRIMARY or SECONDARY role
End of Job Run
not in the PRIMARY or SECONDARY role
End of Job Run
not in the PRIMARY or SECONDARY role
End of Job Run
not in the PRIMARY or SECONDARY role

$Path = "D:\Program Files\test"
$File = "service.log"
$result = Get-ChildItem $Path -recurse | Where-Object { $_.Name -match $File } 
 $a = Get-Content $result.FullName -Tail 10 | Select-string -Pattern "not in the PRIMARY or SECONDARY role" -Quiet

if ($a -eq $True) {

((Get-Content $result.FullName -Raw) -Replace 'not in the PRIMARY or SECONDARY role', 'NOW in the PRIMARY or SECONDARY role') | Set-Content -Path $Path\$File }

現在工作——

$Directory = "D:\Program Files\test"
$Source = "service.log"
$result = Get-ChildItem $Directory -recurse -filter $Source 
if (( Get-Content $result.FullName -Tail 10 | Select-string -Pattern "not in the PRIMARY or SECONDARY role" -Quiet ) ) {
((Get-Content -path $Directory\$Source -Raw) -Replace 'not in the PRIMARY or SECONDARY role', 'NOW in the PRIMARY or SECONDARY role') | Set-Content -Path $Directory\$Source
 }

它只是坐在那里的原因是-Wait參數。 根據Get-Content的文檔:

在所有現有行都為 output 后保持文件打開。在等待期間,Get-Content 每秒檢查一次文件並輸出新行(如果存在)。 您可以按 CTRL+C 中斷等待。 如果文件被刪除,等待也會結束,在這種情況下會報告一個非終止錯誤。 刪除它,腳本將按預期完成。

除此之外,您應該在Get-ChildItem cmdlet 中篩選文件,而不是獲取所有文件,然后使用Where-Object語句進行篩選。 它要快得多,而且是一種很好的做法。

$Path = "D:\Program Files\test"
$File = "service.log"
$result = Get-ChildItem $Path -recurse -filter $File 

我也沒有在任何地方看到$a定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM