PowerShell comes with a powerful yet simple way of monitoring file changes. Let’s assume you have a log file that changes every now and then. This would be a PowerShell script that monitors the log file for changes, and whenever a change occurs, executes some code:

# make sure this points to a log file
$Path = '\\myserver\report2.txt'

Get-Content -Path $Path -Tail 0 -Wait |
ForEach-Object {
    "Detected $_"
}

Just make sure you adjust $path to point to some real log file. Whenever you append text to the file (and save the change), the ForEach-Object loop executes the script block and outputs “Detected ”. This way, you can easily respond to the actual change.

Get-Content does the heavy lifting: -Wait enables the content monitoring, and -Tail 0 makes sure you ignore existing content and look only for newly added text.


Twitter This Tip! ReTweet this Tip!

Anonymous
  • Not sure about now but I know on Windows 7 and in PSv3, the wait option didn't work reliably. The file could be updated and yet powershell would remain unnotified. Sometimes I would have to click on the file's directory in Explorer and then suddenly powershell would respond and process the data.