This is how I load the nested modules in a ListBox.
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<PSObject> psObjects = _ps.Invoke();
foreach (var psObject in psObjects)
{
listBox1.Items.Add(psObject);
}
}
Now, if the user has selected a specific Module, I want to execute the same.
This does not seem to work [although module should be loaded and it should recognize the command] –
_ps.AddCommand(listBox1.SelectedItem.ToString()).Invoke();
Exception:
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.
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)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Update:
Tried this too i.e. loading the module explicitly from the path ->> with no luck –
var path = ((PSModuleInfo) (((PSObject) (listBox1.SelectedItem)).ImmediateBaseObject)).Path;
path=path.Replace("system32", "SysWOW64");
_ps.AddCommand("Import-Module");
_ps.AddParameter(path);
_ps.Invoke();
Exception after Update: [Although Module is present, works perfectly fine in ISE x86 shell]
A parameter cannot be found that matches parameter name
‘C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\MyModules\MyModule1\MyModule1.psm1’.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Got it finally :-
Instead of doing this –
Do this –