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. What is wrong with my test that is not replacing the last 3 lines to "NOW in the PRIMARY or SECONDARY role"
The service.log file has the following lines of syntax:
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
}
CodePudding user response:
The reason it just sits there is the -Wait
parameter. According to the documentation for 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. You can interrupt Wait by pressing 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. 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.