First off, I have a similar question here, but didn't have a direction on solving the problem. With an idea from a poster Andy Arismendi I come up with a possible solution and this is a new problem:
I am running the below script which binds the below code block to the FileChanged event. When a .psm1 module file changes the code block checks if the file is loaded and attempts to reload. If not, it imports the module. However, I am of the opinion that somehow the event is not associated with the current running environment where the intial script that bound the event is running. I have listed the two problems below the code:
# create a FileSystemWatcher on the currect directory
$filter = '*.psm1'
$folder = $PWD
$watcher = New-object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false; EnableRaisingEvents = $true; NotifyFilter = [IO.NotifyFilters]'LastWrite'}
Register-ObjectEvent $watcher Changed -SourceIdentifier FileChanged -Action {
$folder = $PWD
$name = $Event.SourceEventArgs.Name
$filename = $name.Remove($name.IndexOf('.'), 5)
Write-Host $PWD
$loadedModule = Get-Module | ? { $_.Name -eq $filename }
write-host $filename
if ($loadedModule) {
write-host "Reloading Module $folder\$($filename)"
Reload-Module $filename
} else {
write-host "Importing Module $folder\$($filename)"
Import-Module .\$filename
}
}
Problems: 1) When the .psm1 file changes the event runs twice (for one save of the file)
2) Even though it runs the reload/import commands, it must be operating in a different environment as they are never loaded. But all output does go to the current running environment where the script bound the event.
Like I mentioned, I am convinced that somehow the code block is not associated with the current session.