devModulesDirMonitor.psm1
<#
How to use. Add the following code in your project entry point file. function monitorChangesInModules($dir) { startDirMonitor $dir if ($updatedModules) { foreach ($modName in $updatedModules) { Import-Module "$modName" -Force } resetChangedModulesList } } $dirToWatch = '".\myModules"' monitorChangesInModules($dirToWatch) #> function resetChangedModulesList(){ $global:updatedModules = [System.Collections.ArrayList]@() } function startDirMonitor($dir){ if ($null -eq $global:updatedModules) { resetChangedModulesList # out "start dir monitoring!!!" $updatedAction = { Write-Host "File: " $EventArgs.FullPath " " $EventArgs.ChangeType $global:updatedModules.Add($EventArgs.FullPath) $global:updatedModules = [System.Collections.ArrayList]@($updatedModules | Select-Object -Unique) } <# Create a fileWatcher that will monitor the directory and add its attributes#> $fileWatcher = new-object System.IO.FileSystemWatcher $fileWatcher.Path = $dir $fileWatcher.Filter = "*.psm1"; $fileWatcher.IncludeSubdirectories = $true $fileWatcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite, ` [System.IO.NotifyFilters]::FileName , ` [System.IO.NotifyFilters]::DirectoryName <# If a delegate has already been added to the FileWatchers for that event remove it and add the new one. #> if ($ChangedEvent) { $ChangedEvent.Dispose() } $ChangedEvent = Register-ObjectEvent $fileWatcher "Changed" -Action $updatedAction # if ($CreatedEvent) { $CreatedEvent.Dispose() } # $CreatedEvent = Register-ObjectEvent $fileWatcher "Created" -Action $updated # if ($DeletedEvent) { $DeletedEvent.Dispose() } # $DeletedEvent = Register-ObjectEvent $fileWatcher "Deleted" -Action $updated # if ($RenamedEvent) { $RenamedEvent.Dispose() } # $RenamedEvent = Register-ObjectEvent $fileWatcher "Renamed" -Action $renamedAction $fileWatcher.EnableRaisingEvents = $true } } Export-ModuleMember startDirMonitor Export-ModuleMember resetChangedModulesList |