0

通过 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 位!

4

0 回答 0