c# - add-windowsfeature 无法识别

标签 c# windows powershell exception-handling

我正在尝试使用 C# 运行 powershell 命令,但在调用管道时总是出现错误。我想知道是否有人知道为什么我不断收到无法识别的 add-windowsfeature。提前致谢。

private static void RunScript(string name)
{
    InitialSessionState initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new[] { "ServerManager"});
    Runspace runspace = RunspaceFactory.CreateRunspace(initial); 
    // create Powershell runspace

    runspace.Open();

    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");


    Pipeline pipeline = runspace.CreatePipeline();
    Command cm = new Command("Import-module");
    cm.Parameters.Add("name","ServerManager");
    pipeline.Commands.Add(cm);
    Command command = new Command("add-windowsfeature"); 
    command.Parameters.Add(null, name);  
    pipeline.Commands.Add(command);

    var a = pipeline.Invoke();
    foreach (var psObject in a)
    {
        Console.WriteLine(psObject);
    }

    runspace.Close();
}

最佳答案

ServerManager 是一个仅限 64 位的模块(它不存在于 C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules 但将存在于 C:\Windows\System32\WindowsPowerShell\v1.0\Modules)。编译为 x64,您的代码应该可以工作。

关于c# - add-windowsfeature 无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370322/

相关文章:

c# - OpenCV圆圈检测C#实现

c# - 用户 session ID 作为 Ajax 调用中的参数

windows - 如何在 Windows 中收集每个服务名称及其状态?

c++ - 测试 C++ 代码和 IsBadWritePtr

powershell - Exchange Powershell - 如何从内部脚本调用 Exchange 2010 模块?

c# - Razor 框架 - 后端还是前端?

c# - 如何将缩进的文本转换为一行 xml 字符串?

Windows SHARE_INFO_2 结构

Powershell 基本版

Powershell:将 AD MachineName/UserName/IPv4Address 导出到单个 *.csv