Created
January 5, 2024 15:48
-
-
Save Korijn/3f289669892e9d5a686f1b3ba06e6396 to your computer and use it in GitHub Desktop.
Powershell CLI file watcher (put this in your $profile to use it)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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