I'm trying to launch Windows applications using their AppID such as Microsoft.WindowsCalculator_8wekyb3d8bbwe!App which I get by calling Get-StartApps
Currently I can launch the applications but can't get the correct PID
cmd = exec.Command("powershell", "start", `shell:AppsFolder\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App`)
err := cmd.Start()
fmt.Println(cmd.Process.Pid)
This returns the PID of powershell
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe start shell:AppsFolder\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App
Is there a way to launch the application by the AppID and still get the correct PID?
tl;dr
In principle, you can pass
-PassThruto PowerShell'sStart-Process(start) cmd, which returns a process-info object that has an.Idproperty containing the launched process' PID, and output the latter.Unfortunately, with UWP / AppX applications specifically, such as Calculator, this does not work, which is a problem that exists in the underlying .NET APIs, up to at least .NET 6.0 - see GitHub issue #10996.
You can try the following workaround:
Launch the AppX application with
Start-Process, which indirectly creates a process whose name isCalculator(Windows 10) /CalculatorApp(Windows 11).(Get-Process *calc*).Nameafter launching Calculator.Get-Process *calc* | Select-Object Name, Pathwould show the executable path too, but note that this executable should be considered an implementation detail and can not be invoked directly.Return the ID of that
Calculator/CalculatorAppprocess. The fact that Calculator only ever creates one such process in a given user session actually makes identifying that process easy.Note that this means that the PID of a preexisting Calculator process may be returned, which, however, is the correct one, because the transient process launched by
Start-Processsimply delegates creation of a new Calculator window to an existing process.If you wanted to identify the newly created window, more work would be required: You'd have to enumerate the process' windows and identify the one with the highest z-order.
PowerShell code (note: in Windows 11, replace
CalculatorwithCalculatorApp):Note that I've used the URL scheme
calculator:as a simpler way to launch Calculator.Note:
Where-Object SessionId -eq (Get-Process -ID $PID).SessionIdguards against mistakenly considering potentialCalculatorprocesses created by other users in their own sessions (Get-Processreturns all processes running on the local machine, across all user sessions). Filtering by.SessionID, i.e. by the active user session (window station), prevents this problem.As a PowerShell CLI call: