Home > OS >  powershell increase threshold in parallel
powershell increase threshold in parallel

Time:09-22

How do I increase threshold in parallel.

I've done some research where it uses these syntax for increase but unsure how to implement in my code.

 ForEach-Object -throttleLimit 5 -parallel

My code:

 foreach ($User in Import-Csv -Delimiter "," $importCSV) {            
        $Displayname = $User.DisplayName
        $UserPrincipalName = $User.UserPrincipalName
        $MailNickname = $User.MailNickname
        $password = $User.Password
        $SecureStringPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
 
        New-AzADUser -DisplayName $Displayname -UserPrincipalName $UserPrincipalName -Password $SecureStringPassword -MailNickname $MailNickname -ForceChangePasswordNextLogin:$false  | Select-Object -ExpandProperty UserPrincipalName


    
  
}

CodePudding user response:

Have a look at this example showing how a foreach statement can be rewritten into using Foreach-Object -Parallel

foreach ($number in 1..10) {
    $number
    Start-Sleep -Milliseconds 250
}
1..10 | ForEach-Object -Parallel {
    $_   
    Start-Sleep -Milliseconds 250
}

# $_ represents each object being processed 
# $_ synonymous with $number in the foreach example
# Note: When `-ThrottleLimit` is not specified the default is 5.

Your foreach would look like this after conversion

Import-Csv -Delimiter ',' $importCSV |
    ForEach-Object -Parallel {
        $Displayname = $_.DisplayName
        $UserPrincipalName = $_.UserPrincipalName
        $MailNickname = $_.MailNickname
        $password = $_.Password
        $SecureStringPassword = ConvertTo-SecureString -String $password -AsPlainText -Force

        New-AzADUser -DisplayName $Displayname -UserPrincipalName $UserPrincipalName -Password $SecureStringPassword -MailNickname $MailNickname -ForceChangePasswordNextLogin:$false | Select-Object -ExpandProperty UserPrincipalName
    }

This can be cleaned up a little by creating a hash table for the parameters and making use of splatting

Import-Csv -Delimiter ',' $importCSV |
    ForEach-Object -Parallel {
        $params = @{
            Displayname                  = $_.DisplayName
            UserPrincipalName            = $_.UserPrincipalName
            MailNickname                 = $_.MailNickname
            Password                     = ConvertTo-SecureString -String ($_.Password) -AsPlainText -Force
            ForceChangePasswordNextLogin = $false
        }

        New-AzADUser @params | Select-Object -ExpandProperty UserPrincipalName
    }

  • Related