I got one customer who wanted to find all the installed Windows Store App using WPF platform. However, you cannot code in WPF because the current SDK for querying such information only supports UWP, not WPF.
After some research, there is one PowerShell script
Get-AppxPackage -AllUsers which will return all the installed Windows Store apps under all the user accounts in that PC.
So what we will show here is how to use .NET library to call PowerShell scripts.
When I tested on my PC, I created a WPF project based on .NET 4.6. However, my customer’s .NET version is 4.0. If we try to use the dll the same as my path, customer will get the compiler error.
For .NET 4.5 and above:
C:\Program Files(x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll
Other .NET versions:
Add the correct
System.Management.Automation.dllbased on your .NET version.
First we will create a
RunSpacewhich is used to maintain the state between pipelines
Why we are doing this is because we are going to create a instance of
PowerShell, and this instance is one of a pipeline. Then we will be able to manage the state of the PowerShell instance that we created.
Then we can create the
Runspacein the page code behind file.
rs = RunspaceFactory.CreateRunspace();
Now we can call the PowerShell script in the
ButtonClickevent or other events as below:
private void Button_Click(object sender, RoutedEventArgs e)
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
Collection<PSObject> returnedObject = ps.Invoke();
Till now we finished a quite simple demo on how to do this.
If you just run this project, you will get the below error:
At first I thought this is something related to PowerShell restriction permission, but it’s not. Even with default permission, user should also be able to run this command. And this command will have the same error with PowerShell command line window.
After research, I found this error was due to lack of administrator permission. Because you are trying to get the installed Windows Store apps for all users, not current user. That’s why you will have to run the exe file using Admin permission.
Therefore, if you want to debug this program, you will have to run the
exe file by right click on it and choose
Run as Administrator. Then go back to VS and use the
Attach To Process feature under Debug menu.