【问题标题】:PowerShell cmdlet Install-WindowsFeature called from C# errors and is not listed in the collections of commands从 C# 错误调用的 PowerShell cmdlet Install-WindowsFeature 并且未在命令集合中列出
【发布时间】:2012-10-22 23:38:34
【问题描述】:

我正在尝试通过 PowerShell 和 C# 在 Windows Server 2012 系统上安装新功能。尝试调用 Install-WindowsFeature cmdlet 时出现此错误:

术语“Install-WindowsFeature”未被识别为 cmdlet、函数、脚本文件或可运行的程序...

我可以通过 C# 甚至其他一些新的 cmdlet 调用其他 cmdlet。我做了一个 Get-Command 和 Install-WindowsFeature、Remove-WindowsFeature 和 Get-WindowsFeatures 没有列出...但其他大约 980 个。

为什么我不能从我的 C# 程序调用这个 cmdlet,但是当我转到 PowerShell 时它调用它就好了?

runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Install-WindowsFeature");
Collection<PSObject> output = pipeline.Invoke();

【问题讨论】:

  • 那是什么模块?也许它位于默认情况下未导入的模块中,CreateRunspace 的重载。您可以将 ps 模块添加到您传递给 CreateRunspace 的不同重载的 InitialSessionState 对象。
  • 它在 ServerManager 模块中。我从未使用过 InitialSessionState 对象,我将不得不研究一下。
  • @mikez 试过你的建议,还是不行。字符串 [] 模块 = { "服务器管理器" }; InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ImportPSModule(模块); runspace = RunspaceFactory.CreateRunspace(iss);
  • @Matronix:你能解决这个问题吗?

标签: c# powershell visual-studio-2012 windows-server-2012


【解决方案1】:

在您的代码中尝试使用此命令而不是 Install-WindowsFeature:

Invoke-Expression "Powershell -Command {Import-Module ServerManager ; Install-WindowsFeature XXXX}"

【讨论】:

    【解决方案2】:

    尝试在 x64 中编译。在 Visual Studio 中,转到菜单 Project → Properties → Build - Platform Target = x64.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-08
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      相关资源
      最近更新 更多