Forum Discussion
John_Dodo
Apr 29, 2024Brass Contributor
struggling with parralele tasks
Hi, 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.DNSHostN...
LeonPavesic
May 16, 2024Silver Contributor
Hi John_Dodo,
here’s an approach you can use to try accomplish your goal with parallel tasks:
- Setup your computer list and initialize session attempts.
- Use ForEach-Object to iterate over the array and attempt to establish sessions.
- Handle successful connections and log failed attempts.
- 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 {
hostname
} -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."