windowspowershellgoappx

Launch Applications in WIndows using AppID and get the pid


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?


Solution

  • tl;dr

    // Make PowerShell not only launch Calculator, but also
    // determine and output its PID, as described in the next section.
    out, _ := 
            exec.Command(
              `powershell.exe`, 
              `-NoProfile`, 
              `-Command`, 
              `Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID`,
            ).Output()
    
    // Parse stdout output, which contains the PID, into an int
    var pid int
    fmt.Sscanf(string(out), "%d\n", &pid)
    

    You can try the following workaround:

    PowerShell code (note: in Windows 11, replace Calculator with CalculatorApp):

    # Launch Calculator - which may reuse an existing instance and
    # merely create a new *window* - and report the PID.
    Start-Process -ErrorAction Stop calculator:
    (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID
    

    Note that I've used the URL scheme calculator: as a simpler way to launch Calculator.

    Note:

    As a PowerShell CLI call:

    powershell.exe -NoProfile -Command "Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID"