简体   繁体   English

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

[英]Unable to run PowerShell from C#: The 'Get-WindowsOptionalFeature' command was found in the module 'Dism', but the module could not be loaded

I tried to execute the following PowerShell command from my c# application. 我试图从我的C#应用​​程序中执行以下PowerShell命令。

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

But when I run this, the PowerShell raises the following exception: 但是当我运行此命令时,PowerShell会引发以下异常:

The 'Get-WindowsOptionalFeature' command was found in the module 'Dism', but the module could not be loaded. 在模块“ Dism”中找到“ Get-WindowsOptionalFeature”命令,但无法加载该模块。 For more information, run 'Import-Module Dism' 有关更多信息,请运行“导入模块Dism”。

However, when I run the same script from the PowerShell window, it works just fine. 但是,当我从PowerShell窗口运行相同的脚本时,它可以正常工作。 What is the root of my problem? 我的问题的根源是什么? My operating system is Windows 10. 我的操作系统是Windows 10。

PowerShell version: 5 - 1 - 14393 - 953 PowerShell版本:5-1-14393-953

C# Code: 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());
    }
}

尝试在脚本中包含“导入模块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 };";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM