我们使用以下脚本来启动五个进程。它们每个都在命令提示符下运行。我们希望之后能够停止所有进程。我们怎样才能做到这一点?
运行演示.ps1
$global:p = @();
function global:kill-demo {
$global:p | % {
Write-Host "Killing $($_.ProcessName)"
kill $_
Write-Host "$($_.ProcessName) dead"
}
}
# Authorization Server
Push-Location "./AuthorizationServer"
$global:p += Start-Process dotnet -ArgumentList "run" -PassThru
Pop-Location
# Aurelia Application
Push-Location "./AureliaApp"
$global:p += Start-Process npm -ArgumentList "run start" -PassThru
Pop-Location
# Oidc Client JS
Push-Location "./OidcClientJs"
$global:p += Start-Process npm -ArgumentList "run start" -PassThru
Pop-Location
# Resource Server 01
Push-Location "./ResourceServer01"
$global:p += Start-Process dotnet -ArgumentList "run" -PassThru
Pop-Location
# Resource Server 02
Push-Location "./ResourceServer02"
$global:p += Start-Process dotnet -ArgumentList "run" -PassThru
Pop-Location
Run Code Online (Sandbox Code Playgroud)
理想情况下,我们希望能够打开 PowerShell 并执行以下操作。输出表明 PowerShell 正在查找进程并停止它们,尽管命令提示符全部保持打开状态。
PS> .\RunDemo.ps1
PS> kill-demo
Killing dotnet
dotnet dead
Killing cmd
cmd dead
Killing cmd
cmd dead
Killing dotnet
dotnet dead
Killing dotnet
dotnet dead
Run Code Online (Sandbox Code Playgroud)
当我们启动更简单的进程(如 notepad.exe 或 node.exe)而不运行 Web 应用程序时,该脚本确实可以工作。
您可以使用 Get-Help 来发现 PowerShell 命令的许多功能。在这种情况下,get-help start-process -full将描述-PassThru ,它执行以下操作:
-直通
返回 cmdlet 启动的每个进程的进程对象。默认情况下,此 cmdlet 不生成任何输出。
您可以像这样使用它,并且根据您的情况,将 ID 保存在数组或类似的内容中。
$x = Start-Process notepad.exe -PassThru
# wait some time, etc.
Stop-Process -Id $x.Id
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4586 次 |
最近记录: |