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.
1 2 |
while (!(sleep 5)) {if ((gci "web.config").lastwritetime -ge (get-date).addseconds(-5)){$true}} |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
while (!(sleep $seconds)) { $col = gci $path -filter $file -Recurse $dateafter = (get-date).addseconds(-$seconds) $action = $false $col | % { $file=$_ if (($file).lastwritetime -ge $dateafter){ $action = $true } # end if lastwritetime } # end foreach if ($action -eq $true) { $true } # end if action } # end while loop |