Skip to content

Instantly share code, notes, and snippets.

@teyc
Created May 7, 2020 23:15
Show Gist options
  • Select an option

  • Save teyc/e5ec7f0454a61ce50c2c1e02cb1cd8f6 to your computer and use it in GitHub Desktop.

Select an option

Save teyc/e5ec7f0454a61ce50c2c1e02cb1cd8f6 to your computer and use it in GitHub Desktop.
Waits until a file is changed
<#
.SYNOPSIS
Waits until a file changes
.EXAMPLE
.\Wait-FileChangeEvent.ps1 site.scss { taildwindcss site.scss -o output\site.css }
Waits until site.scss changes and runs a script
#>
[CmdletBinding()]
param (
$Pattern = ".",
$Script = $null
)
$item = Get-Item $Pattern
if ($item -is [System.IO.DirectoryInfo])
{
$Directory = $item.FullName
}
else
{
$Directory = $item.Directory.FullName
}
Write-Verbose "Directory $directory"
$item | % { Write-Verbose "item: $_" }
$watcher = new-object System.IO.FileSystemWatcher
$watcher.Path = $Directory
Unregister-Event "FileChanged" -ErrorAction SilentlyContinue
Register-ObjectEvent $watcher "Changed" -SourceIdentifier "FileChanged"
If ($null -ne $Script)
{
While ($true)
{
$events = Wait-Event "FileChanged"
$events | Where-Object {
Write-Verbose "FullPath $($_.SourceEventArgs.FullPath)"
Write-Verbose "Matched Pattern: $( $item -contains (get-item $_.SourceEventArgs.FullPath ) )"
$item -contains (get-item $_.SourceEventArgs.FullPath )
} | ForEach-Object {
& $script
}
$events| Remove-Event
}
Unregister-Event "FileChanged"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment