1

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.

Community
  • 1
  • 1
pghtech
  • 3,642
  • 11
  • 48
  • 73
  • Sorry I haven't had a chance to try your code after you posted it on your other question. Do you have a function named "Reload-Module" somewhere? Reason why I ask is because that is not a cmdlet. If you don't have a function defined for that then you'll either need to pair `remove-module` with an `import-module` or an `import-module` with a `-force` flag. – Andy Arismendi Dec 29 '11 at 16:45
  • @Andy - I have tried that and no better. I did find the following though and not sure how to get around: http://blogs.msdn.com/b/powershell/archive/2008/06/11/powershell-eventing-quickstart.aspx ...the Register-*Event cmdlets support an -Action scriptblock. PowerShell will invoke that scriptblock in the background when your event arrives. These actions invoke in their own module — they can get and set $GLOBAL variables, but regular variable modifications happen in their own isolated environment. – pghtech Dec 29 '11 at 17:29

1 Answers1

0

This is how I load modules:

Get-Module -listavailable| foreach{Import-Module $_.name}
mr.buttons
  • 685
  • 1
  • 9
  • 18