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)
In principle, you can pass 100 to PowerShell's 101 (102) cmd, which returns a process-info object that has an 103 property containing the launched process' PID,并输出后者.
Unfortunately, with UWP / AppX applications specifically, such as Calculator, this does not work, which is a problem that exists in the underlying .NET APIs,最低版本为.NET 6.0-参见GitHub issue #10996.
你可以try 以下workaround种方法:
PowerShell代码:
# 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
请注意,我使用URL方案calculator:
作为启动计算器的更简单方法.
注:
Where-Object SessionId -eq (Get-Process -ID $PID).SessionId
防止错误地认为other users在their own sessions中创建了潜在的Calculator
个进程(Get-Process
跨所有用户会话返回在本地计算机上运行的all个进程).通过.SessionID
进行过滤,即通过活动用户会话(窗口站)进行过滤,可以防止该问题.
作为PowerShell CLI电话:
powershell.exe -NoProfile -Command "Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID"