简体   繁体   English

Powershell 查找和替换脚本

[英]Powershell Find and Replace Script

The pattern match is returning $True so the test I would think should proceed to run the replace, but instead just sits in a no response mode.模式匹配正在返回 $True 所以我认为测试应该继续运行替换,而是只是处于无响应模式。 What is wrong with my test that is not replacing the last 3 lines to "NOW in the PRIMARY or SECONDARY role"我的测试有什么问题没有将最后 3 行替换为“NOW in the PRIMARY or SECONDARY role”

The service.log file has the following lines of syntax: 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 }

Working now -现在工作——

$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
 }

The reason it just sits there is the -Wait parameter.它只是坐在那里的原因是-Wait参数。 According to the documentation for Get-Content :根据Get-Content的文档:

Keeps the file open after all existing lines have been output. While waiting, Get-Content checks the file once each second and outputs new lines if present.在所有现有行都为 output 后保持文件打开。在等待期间,Get-Content 每秒检查一次文件并输出新行(如果存在)。 You can interrupt Wait by pressing CTRL+C.您可以按 CTRL+C 中断等待。 Waiting also ends if the file gets deleted, in which case a non-terminating error is reported.如果文件被删除,等待也会结束,在这种情况下会报告一个非终止错误。 Remove that and the script will complete as expected.删除它,脚本将按预期完成。

Aside from that, you should filter files at the Get-ChildItem cmdlet, not get all files and then filter with a Where-Object statement.除此之外,您应该在Get-ChildItem cmdlet 中筛选文件,而不是获取所有文件,然后使用Where-Object语句进行筛选。 It is much faster, and a good practice.它要快得多,而且是一种很好的做法。

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

I also don't see $a defined anywhere.我也没有在任何地方看到$a定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM