Skip to content

Instantly share code, notes, and snippets.

@Korijn
Created January 5, 2024 15:48
Show Gist options
  • Save Korijn/3f289669892e9d5a686f1b3ba06e6396 to your computer and use it in GitHub Desktop.
Save Korijn/3f289669892e9d5a686f1b3ba06e6396 to your computer and use it in GitHub Desktop.
Powershell CLI file watcher (put this in your $profile to use it)
function Wait-FileChange {
param(
[string]$FilePath,
[string]$Command
)
$AbsPath = (Resolve-Path $FilePath).Path
$IsDir = (Get-Item $AbsPath).PSIsContainer
if ($IsDir) {
$Dir = $AbsPath
$Filter = "*.*"
} else {
$Dir = Split-Path $AbsPath -Parent
$Filter = Split-Path $AbsPath -Leaf
}
$Watcher = New-Object IO.FileSystemWatcher $Dir, $Filter -Property @{
IncludeSubdirectories = $true
EnableRaisingEvents = $true
}
$CommandBlock = [Scriptblock]::Create($Command)
clear
Invoke-Command -ScriptBlock $CommandBlock
[string] $sourceId = New-Guid
try {
$onChange = Register-ObjectEvent $Watcher -EventName Changed -SourceIdentifier $sourceId
while ($true) {
$event = Wait-Event -SourceIdentifier $sourceId
clear
Invoke-Command -ScriptBlock $CommandBlock
Remove-Event -SourceIdentifier $sourceId
}
}
finally {
Unregister-Event -SourceIdentifier $sourceId
$Watcher.Dispose()
}
}
Set-Alias watch Wait-FileChange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment