【问题标题】:Unable to run PowerShell from C#: The 'Get-WindowsOptionalFeature' command was found in the module 'Dism', but the module could not be loaded无法从 C# 运行 PowerShell:在模块“Dism”中找到“Get-WindowsOptionalFeature”命令,但无法加载该模块
【发布时间】:2017-03-31 01:20:01
【问题描述】:

我尝试从我的 c# 应用程序中执行以下 PowerShell 命令。

$check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
if ($check.Installed -eq 'False') {
    Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
}

但是当我运行它时,PowerShell 会引发以下异常:

在模块“Dism”中找到“Get-WindowsOptionalFeature”命令,但无法加载该模块。有关更多信息,请运行“Import-Module Dism”

但是,当我从 PowerShell 窗口运行相同的脚本时,它工作得很好。我的问题的根源是什么?我的操作系统是 Windows 10。

PowerShell 版本:5 - 1 - 14393 - 953

C#代码:

const string psScript = @"$check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
if ($check.Installed -eq 'False') {
    Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
}";

using (var PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript(psScript);
    var PSOutput = PowerShellInstance.Invoke();

    if (PowerShellInstance.Streams.Error.Count > 0)
    {                       
        foreach (var err in PowerShellInstance.Streams.Error)
            logger.LogError(err.ToString());
    }

    foreach (var outputItem in PSOutput)
    {            
        if (outputItem != null)
            logger.LogInfo(outputItem.ToString());
    }
}

【问题讨论】:

  • 你有解决办法吗?

标签: c# powershell


【解决方案1】:

尝试在脚本中包含“Import-Module Dism”,如下所示:

const string psScript = @"Import-Module Dism; $check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45 if ($check.Installed -eq 'False') { Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45 };";

【讨论】:

  • 虽然可能是这种情况,但它在引发该问题的机器上不起作用。它在我的机器上运行良好,但我们有一台 Windows 10 机器无法通过该脚本。我猜是我的 Windows 机器上缺少一个模块。或某处损坏的模块。但为什么它在 PowerShell 命令行应用程序上运行良好,但在 C# 中显示此错误?
  • 是的,您可能没有安装这些模块。尝试在你的win10机器上安装microsoft.com/es-ES/download/details.aspx?id=40855
猜你喜欢
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
相关资源
最近更新 更多