简体   繁体   中英

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 "$Username@clasd.net" `
        -Name "$Firstname $Lastname" `
        -GivenName $Firstname `
        -Department "$Department" `
        -Company "$Company" `
        -EmailAddress "$Username@clasd.net" `
        -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 }

}

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM