Sep 25

PS One-Liner: #3 PowerShell filewatcher

I was asked if I had something to watch a web.config file and if that file changed fire off good old robocopy. That’s a easy one, you ask I roll. Filewatcher coming up.


The while loop is just used for infinite looping purposes only and  executed every five seconds, ‘sleep’ is the alias for ‘start-sleep‘. Sleep does not generate any output so it is always nothing ‘!’ and loops indefinitely. The ‘if’ statement in the loop uses ‘gci’ (‘get-childitem‘) to check the ‘lastwritetime’ and compares that with the current date minus five seconds using the ‘get-date‘ cmdlet. So if the file is changed in the last five seconds then output “true” which of course can be replaced with an action. After that the while loop sleeps again for five seconds, otherwise it will see the change over and over again instead of just once. For one-liner purposes everything is on one line, I recommend to set things to a variable first and beautify your code with proper formatting if you want to make a decent script out of it. Because of extra requirements, I modified the one-liner to script so it could act on any changed web.config file in the website root.