I am using this below script in Powershell (Version is 5.1):
Get-Content -Path path\to\text\file\to\be\read.txt -Wait
Now this continues to read even after the file is getting no update. How can I stop after I find particular line in the text file? Is there any other way to stop this on condition?
You can pipe the output and use foreach to check each line, if the line equals a certain string you can use break
to stop the command:
Get-Content path\to\text\file\to\be\read.txt -wait | % {$_ ; if($_ -eq "yourkeyword") {break}}
For example, if you run the command above and do the following in another shell:
"yourkeyword" | Out-File path\to\text\file\to\be\read.txt -Append
The Get-Content
displays the new line and stops.
Explanation:
| %
- foreach line that is in the file or gets added to the file while the function runs
$_;
- first write out the line of the foreach then do another command
if($_ -eq "yourkeyword") {break}
- if the line of the foreach is equal to the keyword/line you want, stop the Get-Content