Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

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:UsersusernameDesktopGet-ADUserMembers.psm1" 
        $allusers = Get-ADUserMembers -GroupName $_ | Select-Object ParentGroup, Name, EmployeeNumber, Enabled, LastLogonDate, PasswordLastSet
        


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

       
    } 
 


}
question from:https://stackoverflow.com/questions/65892566/how-to-store-value-from-foreach-parallel-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:UsersusernameDesktopGet-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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...