0
votes

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);
}
1
fwiw, I've in the second approach I've now used runspace.SessionStateProxy.PSVariable.GetValue("Error") to confirm that it is producing the same "module not found" error as the first approach. I've also tried specifying the full path of the module. Still, no go.Elroy Flynn

1 Answers

1
votes

Found the problem. I was building to x86 not x64 or "any". Apparently x86 is the default. And of course server2008 was happy to run it in wow64 but the serveradmin module is not available in that context.