【问题标题】:Running PS CMDLet from code return error: "not recognized"从代码运行 PS CMDLet 返回错误:“无法识别”
【发布时间】:2021-05-28 14:33:22
【问题描述】:

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

下面的代码应该给我所有的 Appx 包,但我得到了这个异常:

System.Management.Automation.CommandNotFoundException: '术语 'Get-AppxPackage' 未被识别为 cmdlet、函数的名称, 脚本文件或可执行程序。检查名称的拼写,或 如果包含路径,请验证路径是否正确并尝试 再次。'

提示该命令是在 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 之间可能存在一些不匹配 - 我已经尝试了一些建议,但似乎仍然失败。

【问题讨论】:

  • 尝试InitialSessionState.CreateDefault() - 没有它,会话中的工作很少。仅使用 .Create() 甚至可能会干扰定位 AppX 模块。
  • 嗨@mklement0 - 使用 CreateDefault() 时,我在 PowerShell.Create(sessionState) 中遇到新异常:PlatformNotSupportedException:此平台不支持操作。 (0x80131539)
  • 我怀疑这是由于 nuget 包是版本 7 造成的,它正在尝试加载我的计算机安装的模块版本 5.1 ...

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


【解决方案1】:

我找到了解决办法:

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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2022-08-09
    • 2020-10-05
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多