struggling with parralele tasks

Brass Contributor



I'm trying to improve my code by using parrallele tasks. I'm struggling with testing the connections.


$cpt = get-adcomputers -filter *

$s = New-PSSession -ComputerName $Srv_list.DNSHostName

$WSUSjob = Invoke-Command -session $s {

write-host $(hostname)


} -JobName WSUSjob -AsJob
$j = Get-Job
$results = $j | Receive-Job


I would know how to test a connection with a foreach and a try catch on a SINGLE computer, but what would be the right way of handling the result of the New-Pssession when using it directly on an ARRAY ?


In my example it works and open sessions on answering computers. But I don't know how to retrieve the ones that didn't answer.


Thank you.

1 Reply

Hi @John_Dodo,

here’s an approach you can use to try accomplish your goal with parallel tasks:

  1. Setup your computer list and initialize session attempts.
  2. Use ForEach-Object to iterate over the array and attempt to establish sessions.
  3. Handle successful connections and log failed attempts.
  4. Retrieve job results and process accordingly.

Here's an example script you can use:


$Srv_list = @('Computer1', 'Computer2', 'Computer3') # Replace with your actual list
$successfulSessions = @()
$failedSessions = @()

# Initialize an empty array to store jobs
$jobs = @()

# go over each computer in the list and try to create a PSSession
$Srv_list | ForEach-Object {
    $computer = $_
    try {
        $session = New-PSSession -ComputerName $computer -ErrorAction Stop
        $successfulSessions += $session

        # Create a job to execute a command on the session
        $job = Invoke-Command -Session $session -ScriptBlock {
        } -AsJob -JobName "WSUSjob_$computer"

        # Store the job
        $jobs += $job
    } catch {
        # Log failed connection attempts
        $failedSessions += $computer
        Write-Warning "Failed to connect to $computer: $_"

# Process jobs
$jobs | ForEach-Object {
    $job = $_
    $jobResult = $null
    try {
        $jobResult = Receive-Job -Job $job -ErrorAction Stop
        Write-Output "Job $($job.Id) on $($job.Name) completed with result: $jobResult"
    } catch {
        Write-Warning "Failed to receive job $($job.Id) on $($job.Name): $_"
    } finally {
        # Clean up the job
        Remove-Job -Job $job

# Output results
Write-Output "Successful Sessions: $($successfulSessions.Count)"
Write-Output "Failed Sessions: $($failedSessions.Count)"

# Optionally close all successful sessions
$successfulSessions | ForEach-Object {
    Remove-PSSession -Session $_

Write-Output "All sessions are closed."



Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.

If the post was useful in other ways, please consider giving it Like.

Kindest regards,

Leon Pavesic