Foreach-Object -Parallel return result

LANG Alexis 116 Reputation points
2021-07-09T08:03:09.043+00:00

Hello,

I am working on a script that i would like to execute in parallel but it has to return command results, how can I do this?

Example :
I woulfd like to use the $something var outside of the foreach-object, (here to print all the data gathered in the loop)

$test = "a test"
Import-Csv $CSV_file -Delimiter ";" | ForEach-Object -Parallel {
    Write-host $using:test
    $someting += "some result`n"
} -ThrottleLimit 5

Write-Host $something
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 34,271 Reputation points Microsoft Vendor
    2021-07-09T10:13:24.737+00:00

    Hi,

    You may try this.

    $someting = @{result1=@();result2=@()}  
    $test = "a test"  
    Import-Csv $CSV_file -Delimiter ";" | ForEach-Object -ThrottleLimit 5 -Parallel {  
         Write-host $using:test  
        ($using:someting).result1 += "some result 1 `n"  
    	($using:someting).result2 += "some result 2 `n"  
    }  
    $someting.result1  
    $someting.result2  
    

    Source:
    https://stackoverflow.com/questions/67570734/powershell-foreach-object-parallel-how-to-change-the-value-of-a-variable-outsid

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful