PowerShell via C# PowerShell SDK fails to load ServerManager module on Windows Server 2019.
I am using command Get-WindowsFeature
to find out if component is installed or not.
Exception:
System.Management.Automation.CommandNotFoundException: The 'Get-WindowsFeature' command was found in the module 'ServerManager', but the module could not be loaded. For more information, run 'Import-Module ServerManager'.
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at System.Management.Automation.Runspaces.Pipeline.Invoke()
at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.Invoke()
at Class.IsWindowsFeatureInstalled(String featureName)
Source code:
try
{
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ImportPSModule(new string[] { "ServerManager" });
Runspace powerShellRunscape = RunspaceFactory.CreateRunspace(initialSessionState);
powerShellRunscape.Open();
using PowerShell powerShell = PowerShell.Create();
powerShell.Runspace = powerShellRunscape;
powerShell.AddCommand("Get-WindowsFeature");
powerShell.AddArgument(featureName);
powerShell.Invoke(); // exception
// ....
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Am I missing some configuration?
EDIT (.NET Framework): Based on Mathias comment I created .NET Framework based project.
Using nuget package PowerShellStandard.Library
same source code (just older C# version).
Exception:
The term 'Get-WindowsFeature' 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.
EDIT2: .NET Framework is working, only you have to use 64bit!