我正在尝试构建一个可以列出和删除 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/