2

I'm trying to build a Windows Application (Console or WPF) that can list and remove Appx packages. But i'm running into an exception on my first step.

the following code are supposed to give me all Appx packages, but im getting this exception:

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.'

Suggesting that the command is executed in CMD.exe and not Powershell ?? I'm pretty sure i spelled the CMDLet correct.

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

Any suggestion what i'm missing ?

edit: according to this S.O. Question there can be some mismatch between x86/x64 execution Calling PowerShell cmdlet from C# throws CommandNotFoundException -- I've tried some of the suggestions but it seems to still fail .

Martin Kirk
  • 302
  • 2
  • 13
  • 1
    Try `InitialSessionState.CreateDefault()` instead - without it, little works in the session. Using just `.Create()` may even interfere with locating the `AppX` module. – mklement0 May 27 '21 at 21:34
  • 1
    Hi @mklement0 - when using CreateDefault() im getting a new exception in the PowerShell.Create(sessionState): PlatformNotSupportedException: Operation is not supported on this platform. (0x80131539) – Martin Kirk May 28 '21 at 06:20
  • 1
    I'm suspecting that this is caused by the nuget package being version 7 and it's trying to load my Computer installed Module version 5.1 ... – Martin Kirk May 28 '21 at 06:29

1 Answers1

2

I found the solution:

Powershell 7 has an issue importing Appx Module: https://github.com/PowerShell/PowerShell/issues/14057

the solution is to run the code as a script like this:

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);
        }
    }
}
Martin Kirk
  • 302
  • 2
  • 13