Skip to content

Instantly share code, notes, and snippets.

@MartinMiles
Created December 5, 2021 23:46
Show Gist options
  • Save MartinMiles/39c3751b818b102275f75b359fbf242e to your computer and use it in GitHub Desktop.
Save MartinMiles/39c3751b818b102275f75b359fbf242e to your computer and use it in GitHub Desktop.
Watches at some folder for a child folder being created, then triggers some action
$global:MonitoredPath = 'c:\inetpub\wwwroot'
$global:ExpectedDirectory = 'xp.xconnect'
$global:KeepGoing = $true
$IncludeSubfolders = $true
$AttributeFilter = [IO.NotifyFilters]::DirectoryName
try
{
$watcher = New-Object -TypeName System.IO.FileSystemWatcher -Property @{
Path = $global:MonitoredPath
Filter = '*'
IncludeSubdirectories = $IncludeSubfolders
NotifyFilter = $AttributeFilter
}
$action = {
$details = $event.SourceEventArgs
$Name = $details.Name
$FullPath = $details.FullPath
$OldFullPath = $details.OldFullPath
$OldName = $details.OldName
$ChangeType = $details.ChangeType
$Timestamp = $event.TimeGenerated
if($FullPath -eq "$global:MonitoredPath\$global:ExpectedDirectory")
{
$global:KeepGoing = $false
Write-Host "Folder created !!!"
}
}
$handlers = . { Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action }
$watcher.EnableRaisingEvents = $true
do
{
Wait-Event -Timeout 1
# Write-Host "." -NoNewline
}
while ($global:KeepGoing)
}
finally
{
# this gets executed when user presses CTRL+C:
$watcher.EnableRaisingEvents = $false
# remove the event handlers
$handlers | ForEach-Object { Unregister-Event -SourceIdentifier $_.Name }
$handlers | Remove-Job
$watcher.Dispose()
# Write-Warning "Event Handler disabled, monitoring ends."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment