工作做自我停止工作

时间:2015-07-11 20:37:11

标签: powershell jobs

在这里寻找验证。一份工作可以停止工作吗?我有一个脚本,只要主脚本正在运行(通过传递$ PID),我就创建了一个禁止服务的作业,我现在正在使用这个

Start-Job -name:'SuppressAdAppMgrSvc' -argumentList $id -scriptBlock {
    param (
        $id
    )

    do {
        if ((Get-Service AdAppMgrSvc -errorAction:silentlyContinue).Status -eq 'Running') {
            Stop-Service AdAppMgrSvc -force -warningAction:silentlyContinue -errorAction:silentlyContinue
        }

        Start-Sleep -s 5
        $powershellProcess = Get-Process -id:$id -errorAction:silentlyContinue
    } while ($powershellProcess)

    Stop-Job 'SuppressAdAppMgrSvc' -warningAction:silentlyContinue -errorAction:silentlyContinue
    Remove-Job 'SuppressAdAppMgrSvc' -warningAction:silentlyContinue -errorAction:silentlyContinue

我的想法是工作将会开始,当$PowershellProcess不再存在时,Stop-Job就会运行。但我怀疑Remove-Job不会,因为这是刚刚停止的工作。一般来说,它可能不是一个问题,因为我的脚本完成时会有99%的时间重新启动,但我很好奇是否有处理此问题的模式?或者它是一个边缘案例?

1 个答案:

答案 0 :(得分:0)

您如何期望Remove-Job在已停止的工作中运行?你为什么要从工作中做到这一点呢?

当scriptblock中的代码终止时,作业将自动进入Stopped状态,因此您需要做的就是等待它发生,然后删除作业:

Start-Job -Name 'SuppressAdAppMgrSvc' -ArgumentList $id -ScriptBlock {
  ...
} | Wait-Job | Remove-Job