Justin Merwin
Justin Merwin

Reputation: 103

Adding User to Multiple Security Groups

I've been able to add a user to one group using the below code.

Get-Aduser -filter 'company -eq "1480"' | %{Add-ADGroupMember "HS Students" $_.SamAccountName}

I want to add the user to multiple groups though. HS and HS Students.

Any help would be appreciated.

EDIT 1

so adding to the bottom of my create user script gives me the messages that the user is already part of the groups I'm trying to add to. Any reason why that is happening.

   foreach ($User in $ADUsers)
   {
   #Read user data from each field in each row and assign the data to a  variable as below

$Username   = $User.ID
$Password   = $User.BDATE
$Firstname  = $User.FNAME
$Lastname   = $User.LNAME
$Department = $User.GRD
$Company    = $User.SCHID #This field refers to the OU the user account is to be moved to

# Choose OU
Switch ($Company)
{
    "1480" {$OU = 'OU=students,OU=users,ou=hs,dc=clasd,dc=net'}
    "1479" {$OU = 'OU=students,OU=users,ou=elem,dc=clasd,dc=net'}
}

#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
     #If user does exist, give a warning
     Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
    #User does not exist then proceed to create the new user account
    "Processing started (on " + $date + "): " | Out-File $log -append
    "--------------------------------------------" | Out-File $log -append

    #Account will be created in the OU provided by the $OU variable read from the CSV file
    New-ADUser `
        -SamAccountName $Username `
        -UserPrincipalName "[email protected]" `
        -Name "$Firstname $Lastname" `
        -GivenName $Firstname `
        -Department "$Department" `
        -Company "$Company" `
        -EmailAddress "[email protected]" `
        -Surname $Lastname `
        -Enabled $True `
        -Scriptpath "login.vbs" `
        -DisplayName "$Firstname $Lastname" `
        -Path $OU `
        -AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
        -ChangePasswordAtLogon $true

    #Start-Sleep 5

    # Add User to Groups
    Get-Aduser -filter 'company -eq "1480"' | % { Add-ADGroupMember "HS Students" $_.SamAccountName; Add-ADGroupMember "HS" $_.SamAccountName }

}

}

Upvotes: 1

Views: 1808

Answers (1)

4c74356b41
4c74356b41

Reputation: 72171

So you would need to add a ; after the first command.

Get-Aduser -filter 'company -eq "1480"' | % 
{ Add-ADGroupMember "HS Students" $_.SamAccountName; Add-ADGroupMember "HS" $_.SamAccountName }

You could use that as a 1 liner, if you really want, its just looking nicer the way I formatted it.

Upvotes: 1

Related Questions