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 |
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.
ReTweet this Tip!
This code is a file system level thing and ran in the same process as the logged on user.
Will this work on a virtual desktop? Currently, I am using one which is hosted on windows.
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.
Powered by IDERA