PsWatch: monitoring a directory for changes

Three months ago I published Javascript continuous testing with QUnit, PhantomJS and Powershell and by that time I wrote a very clunky Powershel script to do this. I knew that there was a section of the script useful for other purposes but I was lazy to learn how to write cmdlets in powershell.

Few days ago I was talking with Graeme Forster in twitter and he said:

The world is small!! He actually fork my “gist” at github to do coffee->js transpilation.

So, I decided to create a better general purpose cmdlet and here is pswatch.

To install pswatch you just run this:

iex ((new-object net.webclient).DownloadString("http://bit.ly/Install-PsWatch"))

And in order to use you should import the module and execute watch:

Import-Module pswatch

watch c:\myfolder

The idea of PsWatch is that you must use the standard powershell “pipelining” mechanism, so whenever a file change, you get an object with two things:

  • Path: the full path to the file that has changed.
  • Operation: Created/Renamed/Updated/Deleted*

Note: by default Deleted files are not shown, you have to add the argument –includeDeleted

A more complex script will be something like this:

watch c:\foo\bar
    | Get-Item 
    | Where-Object {$_.Extension -eq ".coffee"}
    | %{ coffee.exe $_.Path -c }

One more tip

As I mention, the installation of the cmdlet fit in a single line… But if you are working on a team you might want to avoid mailing everyone “install this thing if you want to run my script”… So, just write in your script this:

$m = Get-Module -List pswatch 
if(!$m) {
    Write-Host "Uh-Oh you don't have the pswatch cmdlet installed. Let me handle that for you."
    iex ((new-object net.webclient).DownloadString("http://bit.ly/Install-PsWatch"))
} 

Import-Module pswatch

#Your code...

If it is not installed it will be automagically installed. Maybe

I will write another post how to write this type of cmdlets-auto-installed things.


blog comments powered by Disqus
  • Categories

  • Archives