c# - 从代码运行 PS CMDLet 返回错误 : "not recognized"

标签 c# powershell console-application .net-5

我正在尝试构建一个可以列出和删除 Appx 包的 Windows 应用程序(控制台或 WPF)。但我在第一步时遇到了异常。

以下代码应该为我提供所有 Appx 包,但我收到此异常:

System.Management.Automation.CommandNotFoundException: 'The term 'Get-AppxPackage' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.'

建议该命令在 CMD.exe 中执行,而不是在 Powershell 中执行? 我很确定我拼写的 CMDLet 是正确的。

using System.Management.Automation;
using System.Management.Automation.Runspaces;
/* .. */  
var sessionState = InitialSessionState.Create();
sessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
    
sessionState.ImportPSModule("Appx");
    
using (PowerShell powershell = PowerShell.Create(sessionState))
{
      powershell.AddCommand("Get-AppxPackage");
    
       var result = powershell.Invoke();
}

有什么建议我错过了什么吗?

编辑: 根据这个 S.O.问题 x86/x64 执行之间可能存在一些不匹配 Calling PowerShell cmdlet from C# throws CommandNotFoundException -- 我已经尝试了一些建议,但似乎仍然失败。

最佳答案

我找到了解决方案:

Powershell 7 在导入 Appx 模块时出现问题:https://github.com/PowerShell/PowerShell/issues/14057

解决方案是将代码作为脚本运行,如下所示:

var sessionState = InitialSessionState.CreateDefault();
sessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
            
using (PowerShell powershell = PowerShell.Create(sessionState))
{
    powershell.AddScript("Import-Module -Name Appx -UseWIndowsPowershell; Get-AppxPackage");
                
    var results = powershell.Invoke();

    if (powershell.HadErrors)
    {
        foreach (var error in powershell.Streams.Error)
        {
            Console.WriteLine("Error: " + error);
        }
    }
    else
    {
        foreach (var package in results)
        {
            Console.WriteLine(package);
        }
    }
}

关于c# - 从代码运行 PS CMDLet 返回错误 : "not recognized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67729661/

相关文章:

c# - Windows 8.1 ScriptNotify 不工作

powershell - 使用 Powershell 对文本文件进行计数和过滤

c# - Visual Studio 添加控制台应用程序作为引用

c# - 使用 AutoFixture 中的 AutoMock 对构造函数中的响应式(Reactive)代码进行单元测试?

c# - 礼品包装算法

c# - 在 C# 中打印 (wpf)

powershell - 在 powershell 中获取当前用户的 microsoft 帐户名称

string - 在 PowerShell 中拆分字符串

c# - 如何从控制台应用程序返回 List<string>?

C# 斐波那契函数返回错误