You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Start-Job启动的PowerShell作业事件及判断作业完成/失败状态

PowerShell作业事件相关问题解答

核心结论

PowerShell中通过Start-Job创建的作业对象,仅提供StateChanged这一个公开事件,没有专门用于通知作业成功完成或失败的独立事件。

如何查看作业对象的所有事件

要确认作业对象的所有可用事件,可通过Get-Member命令查看:

$myjob = Start-Job { Get-ChildItem }
$myjob | Get-Member -MemberType Event

执行后会返回如下结果,明确只有StateChanged事件:

TypeName: System.Management.Automation.Job

Name          MemberType Definition
----          ---------- ----------
StateChanged  Event      System.EventHandler`1[System.Management.Automation.JobStateChangedEventArgs] StateChanged(System.Object, System.Management.Automation.JobStateChangedEventArgs)

处理作业完成/失败的正确方式

收到StateChanged事件后,必须通过检查作业的State属性来判断具体状态,示例代码如下:

$myjob = Start-Job { 
    # 模拟成功/失败场景,可注释其中一行测试
    Get-ChildItem
    # throw "模拟作业执行失败"
}

$jobEvent = Register-ObjectEvent -InputObject $myjob -EventName StateChanged -Action {
    $job = $Sender
    $newState = $EventArgs.JobStateInfo.State
    switch ($newState) {
        'Completed' {
            Write-Host "作业[$($job.Id)]执行成功"
            # 这里添加成功后要运行的脚本逻辑
        }
        'Failed' {
            Write-Host "作业[$($job.Id)]执行失败,错误信息:$($job.ChildJobs[0].JobStateInfo.Reason.Message)"
            # 这里添加失败后要运行的脚本逻辑
        }
        'Stopped' {
            Write-Host "作业[$($job.Id)]被终止"
        }
    }
}

注意:作业的错误信息通常存储在$job.ChildJobs[0].JobStateInfo.Reason中,因为Start-Job创建的是父作业,实际执行逻辑在子作业里。

可选替代方案

如果不需要异步监听事件,也可以用Wait-Job等待作业完成后直接判断状态:

$myjob = Start-Job { Get-ChildItem }
Wait-Job $myjob | Out-Null

if ($myjob.State -eq 'Completed') {
    Write-Host "作业执行成功"
    # 执行成功后的脚本
} elseif ($myjob.State -eq 'Failed') {
    Write-Host "作业执行失败"
    # 执行失败后的脚本
}

内容的提问来源于stack exchange,提问作者bahrep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:35:17