I'm trying to host powershell and run Get-Windowsfeature which requires the "ServerAdmin" module. The OS is Server 2008 R2. I can run "Import-module ServerAdmin" at the PS comamnd prompt with success, so I know the machine config is good. However, I cannot get it to work in my custom c# host. I've tried two approaches, shown below. The first, using the import-module command, reports the error "The specified module 'ServerAdmin' was not loaded because no valid module file was found in any module directory". The second approach, using InitialSessionState.ImportModule(), also fails. No error is reported from that method, but the get-windowsfeature command remains unrecognized.
First approach:
var ps = PowerShell.Create();
var cmd = ps.AddCommand("Import-Module");
cmd.AddArgument("ServerManager");
ps.Invoke();
Console.WriteLine("errors");
// produces "The specified module 'ServerAdmin' was not loaded because no valid module file was found in any module directory"
foreach (var error in ps.Streams.Error)
{
Console.WriteLine(error.ToString());
}
Second approach:
var ps = PowerShell.Create();
var initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new[]{"ServerManager"});
var runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
ps.Runspace = runspace;
ps.AddCommand("Get-WindowsFeature");
var results = ps.Invoke(); // throws exception because Get-WindowsFeature is not known
foreach (var result in results)
{
Console.WriteLine(result);
}