Martin Kirk
Martin Kirk

Reputation: 341

Running PS CMDLet from code return error: "not recognized"

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 .

Upvotes: 2

Views: 1361

Answers (1)

Martin Kirk
Martin Kirk

Reputation: 341

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

Upvotes: 2

Related Questions