Skip to content

Instantly share code, notes, and snippets.

@unakatsuo
Created January 29, 2016 12:34
Show Gist options
  • Save unakatsuo/3d50ba31da494edd7321 to your computer and use it in GitHub Desktop.
Save unakatsuo/3d50ba31da494edd7321 to your computer and use it in GitHub Desktop.
Watch path and run command if changed.
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,Position=1)]
[string]$WatchPath,
[Parameter(Mandatory=$True,Position=2)]
[string]$Command,
[Parameter(Mandatory=$False)]
[array]$MonitorEvents = @("Created", "Changed", "Deleted", "Renamed")
)
$DebugPreference = "Continue"
$WatchPath = Resolve-Path $WatchPath
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $WatchPath
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $True
$watcher.EnableRaisingEvents = $True
$eventID = @{}
# Reset event subscription
Unregister-Event -SourceIdentifier InotifyWait_*
try {
foreach($e in $MonitorEvents){
$sid = "InotifyWait_{0}" -f $e
$eventID[$e] = Register-ObjectEvent -InputObject $watcher -EventName $e -SourceIdentifier $sid
Write-Debug ("Register-ObjectEvent: {0}, {1}" -f $e,$eventID[$e].Id)
}
Write-Output "Ready to watch $WatchPath ..."
Write-Output "Command: $Command"
while($True) {
$ev = Wait-Event -SourceIdentifier InotifyWait_*
if( $NULL -eq $ev ) {
continue
}
# Dequeue all events.
Remove-Event -SourceIdentifier InotifyWait_*
Write-Output $Command
Invoke-Expression $Command
}
}finally{
Unregister-Event -SourceIdentifier InotifyWait_*
Write-Debug "Unregister-Event InotifyWait_*"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment