PowerShell Genie

Bulk add users to a group from CSV

Script 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Import-Csv reads the file into objects with one property per column, and ForEach-Object calls Add-ADGroupMember once per row.

The script

1PS> $Group = 'Sales' # target group; change to your group name
2PS> Import-Csv .\users.csv | ForEach-Object { Add-ADGroupMember -Identity $Group -Members (Get-ADUser $_.SamAccountName -ErrorAction Stop) -ErrorAction Stop }

Script reader

Inspect before you run

Inspection only

Inspect the script below. It does not run in this browser.

Inspection only — no command has run.

    Show reference output
    1 Name Status Owner
    2 ---- ------ -----
    3 SRV01 Healthy Platform
    4 SRV02 Healthy Platform
    Inspect this example’s structure

    Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

    $Group = 'Sales' # target group; change to your group name Import-Csv .\users.csv | ForEach-Object { Add-ADGroupMember -Identity $Group -Members (Get-ADUser $_.SamAccountName -ErrorAction Stop) -ErrorAction Stop }
    1. Stage 1$GroupPositional values or no named parameters
    2. Stage 2ForEach-ObjectPositional values or no named parameters

      How it works

      Import-Csv reads the file into objects with one property per column, and ForEach-Object calls Add-ADGroupMember once per row. Each row's SamAccountName is resolved through Get-ADUser with -EA Stop first, so a name that does not exist raises a terminating error rather than quietly adding nothing.

      Adapting it

      Collect the resolved users into an array and make one Add-ADGroupMember call with -Members taking the whole array, which turns forty directory round trips into a single operation.

      Requirements

      ActiveDirectory module plus write access to the target group.

      If the result is unexpected

      Bulk group additions fail for some CSV rows or target the wrong accounts.

      Header names, identity formats and group names may not match the command parameters; partial completion is possible.

      1. Validate the CSV columns and resolve one user and group before reviewing the proposed batch.

      Validate the result

      Each input row has an individual result and successful additions are confirmed in membership.

      Keep the check reliable

      Validate the input contract and make repeat runs check existing membership first.

      Primary documentation

      Active Directory PowerShell documentation

      Continue
      Genie guideBulk add users to a group from CSV

      Import-Csv reads the file into objects with one property per column, and ForEach-Object calls Add-ADGroupMember once per row.