无法从C#运行PowerShell:在“Dism”模块中找到了“Get-WindowsOptionalFeature”命令,但无法加载模块

时间:2017-03-28 20:29:40

标签: c# powershell

我尝试从我的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());
    }
}

1 个答案:

答案 0 :(得分: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 };";