PowerShell: Add Users to Active Directory Group from Text File

A customer recently requested a PowerShell script, to add Active Directory users to a security group. The list of users would come from a text file that resides on the filesystem. To that end, I wrote a short PowerShell script that does just that, complete with parameter validation.

#requires -version 4.0
#requires -Module ActiveDirectory
param (
      [Parameter(Mandatory = $true)]
      [ValidateScript({ if (Get-ADGroup -Identity $PSItem) { $true; }; })]
      [string] $GroupName
    , [Parameter(Mandatory = $true)]
      [ValidateScript({ Test-Path -Path $PSItem; })]
      [System.IO.FileInfo] $Path
)

$UserList = Get-Content -Path $Path;
foreach ($User in $UserList) {
    $ADUser = Get-ADUser -Identity $User -ErrorAction SilentlyContinue;
    if ($ADUser) {
        Add-ADGroupMember -Identity $GroupName -Members $ADUser;
    }
    $ADUser = $null;
} 

Using the Script

PowerShell ISE: Add-UsersToADGroup
Running script from PowerShell ISE

To use the script from PowerShell Integrated Scripting Editor (ISE), follow these steps:

  1. Create a text file (eg. c:\test\UserList.txt) and add one user account to each line
  2. Launch the PowerShell ISE
  3. Copy and paste the script into the PowerShell ISE, and press F5 to invoke it
  4. You will be prompted for the Active Directory security group’s name
  5. You will be prompted for the full path to the text file that contains the list of users

Alternatively, you can follow these steps to execute the script from the PowerShell console:

  1. Create a text file (eg. c:\test\UserList.txt) and add one user account to each line
  2. Save the script to a file with a .ps1 extension (eg. c:\test\AddADGroupMembers.ps1)
  3. From a PowerShell console prompt, use either call operator (& or .) to invoke the script
  4. You will be prompted for the Active Directory security group’s name
  5. You will be prompted for the full path to the text file that contains the list of users

& c:\test\AddADGroupMembers.ps1