当其中一个作业失败时,powershell作业会话中止

时间:2018-04-24 11:46:00

标签: powershell powershell-v3.0

您好我正在PowerShell中编写一个可以并行执行的作业脚本。

下面附带的示例代码用于模拟场景。当我们将参数传递为" b"时脚本失败到了scriptblock。

$createZip = {
    Param ( [String] $source, [String] $zipfile )

    if ($source -eq "b") {
        throw "Failed to create $zipfile"
    }
    else {
        return "Successfully created $zipfile"
    }
}

$jobs = @()                          
$sources = "a", "b", "c"

foreach ($source in $sources) {
    Start-Job -Name $source -ScriptBlock $createZip -ArgumentList $source, "${source}.zip"
}


Get-Job | Wait-Job | Out-Null

如果任何一项工作失败,我需要中止所有正在运行的工作。我如何在powershell工作中做到这一点。

1 个答案:

答案 0 :(得分:2)

如果你想取消所有失败的工作,你可以这样做:

$jobs = Get-Job

while ('Running' -in $jobs.State) {
    if ('Failed' -in $jobs.State) {
        $jobs | Stop-Job | Remove-Job
        break
    }

    Start-Sleep -Milliseconds 500
}

编辑:
以下是您的代码应该的示例:

$createZip = {
    param(
        [Parameter(Position = 0, Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $source,

        [Parameter(Position = 1, Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $zipfile
    )

    if ($source -eq 'b') {
        throw "Failed to create $zipfile"
    } else {
        "Successfully created $zipfile"
    }
}

$sources = 'a', 'b', 'c'    
$jobs = foreach ($source in $sources) {
    Start-Job -Name $source -ScriptBlock $createZip -ArgumentList $source, "$source.zip"
}

'Queued'

while ('Running' -in $jobs.State) {
    $jobs.State

    if ('Failed' -in $jobs.State) {
        $jobs | Stop-Job | Remove-Job
        'Aborting jobs'
        break
    }

    Start-Sleep -Milliseconds 500
}