在 PowerShell 中继续代码之前如何等待可执行文件打开?

问题描述 投票:0回答:2

我做了很多研究,但似乎找不到任何解决方案。

我尝试过使用

Wait-Event -SourceIdentifier "ProcessStarted"
,但它似乎根本不起作用。它只是无限等待,不会让代码恢复。如果有办法等待可执行文件启动或等待特定的启动,请帮助兄弟!

powershell shell executable
2个回答
1
投票

据我所知,你有一个脚本,想暂停它直到某个进程开始,一旦它开始继续脚本的其余部分。

一个快速而肮脏的解决方案是使用

get-process
并查询进程名称,在这个例子中我使用
vlc
。输出将是
$null
直到进程启动,一旦启动循环将退出。这仅在进程尚未运行时才有效。例如,如果您已经在运行 Chrome,并且您正在尝试寻找该进程的新实例,则此代码将不起作用。

# some code
$processName = "vlc"
# wait until process starts
while ((Get-Process -name $processName -ErrorAction SilentlyContinue) -eq $null)
{
    write-host "waiting for process to start to continue"
    Start-Sleep -Seconds 2
}

# continue code 
write-host "Process started"

--

示例输出

.\wait_for_process.ps1
waiting for process to start to continue
waiting for process to start to continue
waiting for process to start to continue
waiting for process to start to continue
Process started

0
投票

操作系统不会神奇地向您宣布进程启动事件 - 您需要指定您想要了解的确切事件,然后注册目标事件:

# define an event polling query - this will poll WMI for new process creations every 2 seconds
$processCreationEventQuery = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA Win32_Process"

# add event registration to make PowerShell consume the event from WMI
Register-CimIndicationEvent -Query $processCreationEventQuery -SourceIdentifier ProcessStarted

现在我们已经设置了活动注册,

Wait-Event
将起作用:

Wait-Event -SourceIdentifier ProcessStarted

如果你想等待更具体的进程启动,修改查询过滤器,例如:

$processCreationEventQuery = @"
SELECT TargetInstance 
  FROM __InstanceCreationEvent 
WITHIN 2 
 WHERE TargetInstance ISA Win32_Process
   AND TargetInstance.Name LIKE '%RelevantProcessNameGoesHere%'
"@
© www.soinside.com 2019 - 2024. All rights reserved.