Skip to Content

Tag: Powershell

    File Watcher (PowerShell)

    I wanted to run a script every time a file changed. There’s a bunch of tools to do this for Linux, but I’m on Windows (because reasons). I found a PowerShell module, installed it, and got to work.

    function Enter-Watcher {
      Param (
        [Parameter(Mandatory=$true, Position=0)]
      #Cleanup of previous uses. Remove past watchers of this type, to eliminate double-events
      $e = "$SourceIdentifier-emit" 
      Remove-Job -name $e,$SourceIdentifier -Force 2>$null # -Force removes not-stopped jobs too
      Remove-FileSystemWatcher -SourceIdentifier $SourceIdentifier
      $fs = New-FileSystemWatcher -SourceIdentifier $SourceIdentifier -Path $Path -Filter $Filter -Action {
        if($event.messageData.ChangeType -eq "Changed") {
          $x = "$($event.SourceIdentifier)-emit"
          New-Event -SourceIdentifier $x -MessageData $event.messageData.fullpath
      $job = Register-EngineEvent -SourceIdentifier $e -Action $Scriptblock
      while($true) {
        receive-job $job
    function Remove-AllWatchers {
      Get-FileSystemWatcher | Remove-FileSystemWatcher

    Call it like: