C# PowerShell SDK 経由の PowerShell は、Windows Server 2019 で ServerManager モジュールをロードできません。
コマンドGet-WindowsFeature
を使用して、コンポーネントがインストールされているかどうかを確認しています。
例外:
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)
ソースコード:
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);
}
いくつかの構成がありませんか?
編集 (.NET Framework): Mathias のコメントに基づいて、.NET Framework ベースのプロジェクトを作成しました。
nuget パッケージ PowerShellStandard.Library の使用
同じソース コード (古い C# バージョンのみ)。
例外:
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 は動作しています。64 ビットを使用する必要があります。