while 循环的 PowerShell 后台作业处理
PowerShell Background-Job Processing of a while loop
我正在尝试查看后台作业中的进程,但我想我没有正确理解 powershell 中的后台处理。我假设那是因为我的脚本不想工作。
$target = "firefox"
$Watch = {
while (1) {
sleep -Milliseconds 100
if(!((get-process $target -ErrorAction SilentlyContinue).Responding -eq $true))
{
Get-Job -name $target | Stop-Job
break
}
}
}
Start-Job -Name $target -ScriptBlock $Watch
在我看来,这个脚本应该每 100 毫秒控制我的 "firefox" 进程的 "responding" 属性,如果 firefox 挂起或关闭,它应该停止后台作业。
如果我执行这个脚本然后关闭我的 firefox 进程,作业仍然是 运行ning。它似乎并不关心我的 Stop-Job
命令。
如果我执行这个 scipt 而没有像这样的任何工作,它就像一个魅力。
$target = "firefox"
while (1) {
sleep -Milliseconds 100
if(!((get-process $target -ErrorAction SilentlyContinue).Responding -eq $true))
{
Write-Host "Hello"
break
}
}
如果我 运行 这个脚本有作业,并在控制台中执行 get-job -name $target | stop-job
部分,它也可以工作。所以它只是不想在 运行ning 作为后台作业时执行我的 if () {scriptblock}
。
是否不可能 运行 后台作业中的循环?
您正试图从作业内部停止作业...这是不可能的
PowerShell 作业使用不同的进程 ID 并且完全分离,即使您从作业接收数据,数据也是 "Deserialized" 这意味着它不是真实对象只是它的副本。
因此,如果您的目的是在 firefox 进程没有响应时停止作业,您可以创建一个简单的作业,如下所示:
进程正在响应和未响应时...
$Job = Start-Job {
## Monitor the job and wait until it stop responding...
while ((Get-Process firefox).Responding) {sleep -Milliseconds 100}
## do whatever you want, when it stopped responding...
if (!(Get-Process firefox).Responding) {
Stop-Process firefox
Start-Process firefox
}
}
我正在尝试查看后台作业中的进程,但我想我没有正确理解 powershell 中的后台处理。我假设那是因为我的脚本不想工作。
$target = "firefox"
$Watch = {
while (1) {
sleep -Milliseconds 100
if(!((get-process $target -ErrorAction SilentlyContinue).Responding -eq $true))
{
Get-Job -name $target | Stop-Job
break
}
}
}
Start-Job -Name $target -ScriptBlock $Watch
在我看来,这个脚本应该每 100 毫秒控制我的 "firefox" 进程的 "responding" 属性,如果 firefox 挂起或关闭,它应该停止后台作业。
如果我执行这个脚本然后关闭我的 firefox 进程,作业仍然是 运行ning。它似乎并不关心我的 Stop-Job
命令。
如果我执行这个 scipt 而没有像这样的任何工作,它就像一个魅力。
$target = "firefox"
while (1) {
sleep -Milliseconds 100
if(!((get-process $target -ErrorAction SilentlyContinue).Responding -eq $true))
{
Write-Host "Hello"
break
}
}
如果我 运行 这个脚本有作业,并在控制台中执行 get-job -name $target | stop-job
部分,它也可以工作。所以它只是不想在 运行ning 作为后台作业时执行我的 if () {scriptblock}
。
是否不可能 运行 后台作业中的循环?
您正试图从作业内部停止作业...这是不可能的
PowerShell 作业使用不同的进程 ID 并且完全分离,即使您从作业接收数据,数据也是 "Deserialized" 这意味着它不是真实对象只是它的副本。
因此,如果您的目的是在 firefox 进程没有响应时停止作业,您可以创建一个简单的作业,如下所示:
进程正在响应和未响应时...
$Job = Start-Job {
## Monitor the job and wait until it stop responding...
while ((Get-Process firefox).Responding) {sleep -Milliseconds 100}
## do whatever you want, when it stopped responding...
if (!(Get-Process firefox).Responding) {
Stop-Process firefox
Start-Process firefox
}
}