title: Powershell/C#: Import and Invoke Nested Modules
body: <p>This is how I load the nested modules in a ListBox.</p>
  
  <pre><code>public partial class Form1 : Form
      {
          readonly PowerShell _ps = PowerShell.Create();
          public Form1()
          {
              InitializeComponent();
  
              _ps.AddScript("Import-Module MyModules");
              _ps.AddScript("(Get-Module MyModules).NestedModules");
              Collection&lt;PSObject&gt; psObjects = _ps.Invoke();
  
              foreach (var psObject in psObjects)
              {
                  listBox1.Items.Add(psObject);
              }
  }
  </code></pre>
  
  <p>Now, if the user has selected a specific Module, I want to execute the same. </p>
  
  <p>This does not seem to work [although module should be loaded and it should recognize the command] - </p>
  
  <pre><code>_ps.AddCommand(listBox1.SelectedItem.ToString()).Invoke();
  </code></pre>
  
  <p><strong>Exception:</strong></p>
  
  <blockquote>
    <p>The term 'MyModule1' is not recognized as the name of a cmdlet,
    function, script file, or operable program. Check the spelling of the
    name, or if a path was included, verify that the path is correct and
    try again.</p>
  </blockquote>
  
  <p>I assume that the Module would have been loaded in the memory by now and I have to just Invoke it. (Note that the Module Name and command name are same here)</p>
  
  <p><em><strong>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////</em></strong></p>
  
  <p><strong>Update:</strong>
  Tried this too i.e. loading the module explicitly from the path ->> with no luck -</p>
  
  <pre><code>    var path = ((PSModuleInfo) (((PSObject) (listBox1.SelectedItem)).ImmediateBaseObject)).Path;
      path=path.Replace("system32", "SysWOW64");
  
      _ps.AddCommand("Import-Module");
      _ps.AddParameter(path);
      _ps.Invoke();
  </code></pre>
  
  <p><strong>Exception after Update:</strong> [Although Module is present, works perfectly fine in ISE x86 shell]</p>
  
  <blockquote>
    <p>A parameter cannot be found that matches parameter name
    'C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\MyModules\MyModule1\MyModule1.psm1'.</p>
  </blockquote>
  
  <p><em><strong>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////</em></strong></p>