Apr 29 2024 04:48 AM
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.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.
May 15 2024 11:56 PM
Hi @John_Dodo,
here’s an approach you can use to try accomplish your goal with parallel tasks:
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."