将用户添加到多个安全组

时间:2016-11-14 19:39:57

标签: powershell active-directory

我已经能够使用以下代码将用户添加到一个组。

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

我想将用户添加到多个组中。 HS和HS学生。

任何帮助都将不胜感激。

编辑1

因此添加到我的创建用户脚本的底部会给我一些消息,表明用户已经是我尝试添加的组的一部分。发生这种情况的原因。

   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 }

}

}

1 个答案:

答案 0 :(得分:0)

因此您需要在第一个命令后添加;

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

如果你真的想要的话,可以用它作为1个衬垫,它看起来比我格式化的方式更好。