Search code examples
powershellpowershell-3.0

powershell job session abort when one of the job fail


Hi I am writing a job script in powershell which can execute it in parallel.

A sample code attached below to simulate the scenario. The script fail when we pass the argument as "b" to the 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

If anyone of the job is getting failed, I need to abort all the running jobs. How do i do that in powershell job.


Solution

  • If you want to cancel all jobs on the failure of one, you can do that like so:

    $jobs = Get-Job
    
    while ('Running' -in $jobs.State) {
        if ('Failed' -in $jobs.State) {
            $jobs | Stop-Job | Remove-Job
            break
        }
    
        Start-Sleep -Milliseconds 500
    }
    

    Edit:
    Here's an example of what your code should look like:

    $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
    }