Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7627335
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T05:26:43+00:00 2026-05-31T05:26:43+00:00

Hi all! I’ve been looking for a way to make my script more efficient

  • 0

Hi all!

I’ve been looking for a way to make my script more efficient and I’ve come to the conclusion (with help from the nice people here on StackOverflow) that Start-Job is the way to go.

I have the following foreach-loop that I would like to run simultanously on all the servers in $servers. I have problems understanding how I actually collect the information returned from Receive-Job and add to $serverlist.

PS: I know that I am far away from getting this nailed down, but I would really appreciate some help starting out as I am quite stumped on how Start-Job and Receive-Job works..

# List 4 servers (for testing)
$servers = Get-QADComputer -sizelimit 4 -WarningAction SilentlyContinue -OSName *server*,*hyper*

# Create list
$serverlistlist = @()

# Loop servers
foreach($server in $servers) {

    # Fetch IP
    $ipaddress = [System.Net.Dns]::GetHostAddresses($Server.name)| select-object IPAddressToString -expandproperty IPAddressToString

    # Gather OSName through WMI
    $OSName = (Get-WmiObject Win32_OperatingSystem -ComputerName $server.name ).caption

    # Ping the server
    if (Test-Connection -ComputerName $server.name -count 1 -Quiet ) {
        $reachable = "Yes"
    }

    # Save info about server
    $serverInfo = New-Object -TypeName PSObject -Property @{
        SystemName = ($server.name).ToLower()
        IPAddress = $IPAddress
        OSName = $OSName
    }
    $serverlist += $serverinfo | Select-Object SystemName,IPAddress,OSName
}

Notes

  • I am outputting $serverlist to a csv-file at the end of the script
  • I list aprox 500 servers in my full script
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T05:26:44+00:00Added an answer on May 31, 2026 at 5:26 am

    Since your loop only needs to work with a string it’s easy to turn it into a concurrent script.

    Below is an example of making making your loop use background jobs to speed up processing.

    The code will loop through the array and spin up background jobs to run the code in the script block $sb. The $maxJobs variable controls how many jobs run at once and the $chunkSize variable controls how many servers each background job will process.

    Add the rest of your processing in the script block adding whatever other properties you want to return to the PsObject.

    $sb = {
        $serverInfos = @()
        $args | % {
            $IPAddress = [Net.Dns]::GetHostAddresses($_) | select -expand IPAddressToString
            # More processing here... 
            $serverInfos += New-Object -TypeName PsObject -Property @{ IPAddress = $IPAddress }
        }
        return $serverInfos
    }
    
    [string[]] $servers = Get-QADComputer -sizelimit 500 -WarningAction SilentlyContinue -OSName *server*,*hyper* | Select -Expand Name
    
    $maxJobs = 10 # Max concurrent running jobs.
    $chunkSize = 5 # Number of servers to process in a job.
    $jobs = @()
    
    # Process server list.
    for ($i = 0 ; $i -le $servers.Count ; $i+=($chunkSize)) {
        if ($servers.Count - $i -le $chunkSize) 
            { $c = $servers.Count - $i } else { $c = $chunkSize }
        $c-- # Array is 0 indexed.
    
        # Spin up job.
        $jobs += Start-Job -ScriptBlock $sb -ArgumentList ( $servers[($i)..($i+$c)] ) 
        $running = @($jobs | ? {$_.State -eq 'Running'})
    
        # Throttle jobs.
        while ($running.Count -ge $maxJobs) {
            $finished = Wait-Job -Job $jobs -Any
            $running = @($jobs | ? {$_.State -eq 'Running'})
        }
    }
    
    # Wait for remaining.
    Wait-Job -Job $jobs > $null
    
    $jobs | Receive-Job | Select IPAddress
    

    Here is the version that processes a single server per job:

    $servers = Get-QADComputer -WarningAction SilentlyContinue -OSName *server*,*hyper*
    
    # Create list
    $serverlist = @()
    
    $sb = {
        param ([string] $ServerName)
        try {
            # Fetch IP
            $ipaddress = [System.Net.Dns]::GetHostAddresses($ServerName)| select-object IPAddressToString -expandproperty IPAddressToString
    
            # Gather OSName through WMI
            $OSName = (Get-WmiObject Win32_OperatingSystem -ComputerName $ServerName ).caption
    
            # Ping the server
            if (Test-Connection -ComputerName $ServerName -count 1 -Quiet ) {
                $reachable = "Yes"
            }
    
            # Save info about server
            $serverInfo = New-Object -TypeName PSObject -Property @{
                SystemName = ($ServerName).ToLower()
                IPAddress = $IPAddress
                OSName = $OSName
            }
            return $serverInfo
        } catch {
            throw 'Failed to process server named {0}. The error was "{1}".' -f $ServerName, $_
        }
    }
    
    # Loop servers
    $max = 5
    $jobs = @()
    foreach($server in $servers) {
        $jobs += Start-Job -ScriptBlock $sb -ArgumentList $server.Name
        $running = @($jobs | ? {$_.State -eq 'Running'})
    
        # Throttle jobs.
        while ($running.Count -ge $max) {
            $finished = Wait-Job -Job $jobs -Any
            $running = @($jobs | ? {$_.State -eq 'Running'})
        }
    }
    
    # Wait for remaining.
    Wait-Job -Job $jobs > $null
    
    # Check for failed jobs.
    $failed = @($jobs | ? {$_.State -eq 'Failed'})
    if ($failed.Count -gt 0) {
        $failed | % {
            $_.ChildJobs[0].JobStateInfo.Reason.Message
        }
    }
    
    # Collect job data.
    $jobs | % {
        $serverlist += $_ | Receive-Job | Select-Object SystemName,IPAddress,OSName
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

All the code/commands below are part of a PHP script that processes images from
All, I have some script tags that are not working in Wordpress. If I
All programs that I develop utilize the default Windows Design template: Besides from changing
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
All, I have the following code: $fetch = mysql_query(SELECT * FROM calendar_events where event_status='booked'
All along I've been testing on an Android 2 version ported to x86 (which
All I want is to make a simple user password login. I have put
All, I wanted to know how I could pass a $variable from view, for
I have a text area in my form which accepts all possible characters from
All the examples I can find using DLLImport to call C++ code from C#

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.