问题
I have a computer that is logging events from a device on a serial port. Putty is logging them to a file.
I used to have this running on a Linux machine. Basically would tail -f event.log >> script.sh
This was the *nix script
#!/bin/bash
outfile=sras_pages.log
while read -r line
do
IFS=' ' read -ra split <<< "$line"
[[ ${split[1]} == AC/BATT_PWR ]] && echo "${line:9:29}"
[[ ${split[1]} == COMM-FAULT ]] && echo "${line:9:29}"
done >> "$outfile"
Basically I want to forward only character positions 9-29 that contain the two strings above to a file that is monitored by a paging terminal.
The Linux option is gone now and I'm stuck with windows. I've only just learned about windows PowerShell and have been trying to muck my way through it via examples i find online.
I started with this:
Get-Content -Path C:\temp\SRAS\alarm.log -tail 1 -Wait
Which gives me the tail -f
functionality I got with linux. The problem is I can't figure out how to feed the output of this command into another PowerShell script.
I then cobbled this together
$p = @("AC/BATT_PWR","COMM-FAULT")
Get-Content -Path C:\temp\SRAS\alarm.log -tail 1 -Wait | Select-String -Pattern $p -SimpleMatch | Set-Content C:\temp\SRAS\sras_pages.log
Which works, EXCEPT the file sras_pages.log is only written to once I Ctrl+C in the powershell to stop it from running.
What I need is to monitor a log file that is updating regularly, and any events that match a string to be appended to a separate file when they happen.
I don't know enough about powershell to do this and am looking for some help.
Much appreciated.
回答1:
Set-Content
overwrites the file's contents, so it waits for all the content before it flushes and writes everything to the file. Add-Content
appends to the file, which would fit better for a script that will continue to write over time, but just like Set-Content
, it locks the file and flushes when the script is done or cancelled.
Out-File
however also supports appending, and it does not lock the file. So you could try replacing your Set-Content
command with:
Out-File -FilePath "C:\temp\SRAS\sras_pages.log" -Append
来源:https://stackoverflow.com/questions/28005726/filter-string-from-live-updating-log-file-using-windows-powershell