Search code examples
powershellforeachparallel-processingparallel.foreach

How to store value from foreach parallel Powershell


I am a powershell beginner and I just want to know what would be the best way to store all the value of my $allusers variable into one object? I am running the command inside the foreach parallel and I cant store all of the data into my global variable. Thank you so much in advance for someone who already faced this issue.

Function Get-Members {
    param ( 
        [Parameter(Mandatory = $true)][String]$FileName,
        [Parameter(Mandatory = $true)][String]$searchFileURL
    )
  
    $storageHolder = @()
    
    $groupList = Get-Content $searchFileURL  #| ForEach-Object { $_ }
    $groupList |  ForEach-Object -Parallel {
        
       
        Import-Module -Name "C:\Users\username\Desktop\Get-ADUserMembers.psm1" 
        $allusers = Get-ADUserMembers -GroupName $_ | Select-Object ParentGroup, Name, EmployeeNumber, Enabled, LastLogonDate, PasswordLastSet
        


        $storageHolder +=  $allusers <------------ This is not working even the $Using:storageHolder

       
    } 
 


}

Solution

  • Simply output the data from the ForEach-Object block and assign to a variable that will collect all outputs, as showcased by example 12.

    $storageHolder = $groupList | ForEach-Object -Parallel {     
       
        Import-Module -Name "C:\Users\username\Desktop\Get-ADUserMembers.psm1" 
        Get-ADUserMembers -GroupName $_ | Select-Object ParentGroup, Name, EmployeeNumber, Enabled, LastLogonDate, PasswordLastSet       
    }
    

    PowerShell will automatically create and expand an array, if there are multiple objects output from the ForEach-Object loop.