以特殊名称启动进程,或杀死它的句柄

start-process with a special name, or handle to kill it

我们有许多 node.js 程序都是用 powershell 创建的。我们使用启动进程在后台生成 node.js 可执行文件 (node.exe)。

我们想给每一个一个不同的 "handle" 以便我们以后可以使用 powershell 命令 stop-process 来杀死它们。例如启动进程-名称 'wServer' 要终止的 powershell 脚本将与启动脚本不同,不同的用户可能会使用它。

我对如何识别每个 node.exe 不同之处感到困惑。不同的不是可执行文件,而是 app.js

的路径

以下是我们如何启动其中之一:

$reg = Get-Item -Path "hklm:\SOFTWARE\us\EGPL\GeoLibrarian" 
$path = $reg.GetValue('LibrarianPath').ToString() 
$sixtyfour = [Environment]::Is64BitProcess

# Now start running Watson
$node = "C:\Program Files\nodejs\node.exe" 
$arg = "app.js"
$dir = "$path\Watson"
start-process -WorkingDirectory $dir $node $arg
Write-Host "64-Bit Powershell: "$sixtyfour
Write-Host "PowerShell Version: "$PSVersionTable.PSVersion
Write-Host "Watson running in background"

现在,我可以通过此序列杀死以唯一 window 开头的那些,我认为在 powershell 中启动的那些不会有 window.

Write-Host "Kill watson task"
$watson = get-process | where-object {$_.MainWindowTitle -eq 'WatsonJS'}
Stop-Process -Id $watson.Id -ErrorAction SilentlyContinue

一种方法是使用-PassThru参数,这使得Start-Process到return一个可以用来控制进程的对象。完成该过程后,将对象通过管道传递给 Stop-Process(或调用对象的 Kill() 方法)

如果您需要跨 PS 个会话存储对象,您可以使用 Export-Clixml 将变量保存到 XML 文件。稍后,使用 Import-Clixml.

重新水化变量 PS 会话 #1
$proc = Start-Process notepad -Passthru
$proc | Export-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
PS 会话 #2
$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process