且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Powershell将新用户添加到Active Directory时如何包括组

更新时间:2023-11-04 15:47:52

New-ADUser cmdlet有很多参数,但是没有用于设置组成员身份的参数。
这需要在按如下所示创建用户之后完成。

The New-ADUser cmdlet has a lot of parameters, but there is no parameter to set the group membership. This needs to be done after the user is created like below.

我对代码进行了一些更改并使用了使用splatting 可以更好地阅读并避免使用难以理解的背景。
此外,也不需要先将CSV文件中的所有字段捕获到变量中。只需直接将它们用作参数即可。

I have changed the code somewhat and used splatting for better reading and to avoid having to use the hard-to-see backtick. Also, there is no need to capture all fields from the CSV file into variables first. Just use them directly for the parameters.

# Import active directory module for running AD cmdlets
Import-Module activedirectory

#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\upload\testbulkupload2.csv
$groups  = 'DRC VPN Users', 'Echo Prod Users'

#Loop through each row containing user details in the CSV file 
foreach ($User in $ADUsers) {
    # Read user data from each field in each row
    # the username is used more often, so to prevent typing, save that in a variable
    $Username       = $User.username

    # 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

        # Account will be created in the OU provided by the $OU variable read from the CSV file

        # create a hashtable for splatting the parameters
        $userProps = @{
            SamAccountName        = $username
            UserPrincipalName     = '{0}@lon.cloud' -f $username
            GivenName             = $User.firstname
            Surname               = $User.lastname
            Name                  = '{0} {1)' -f $User.firstname, $User.lastname
            DisplayName           = '{0}, {1}' -f $User.lastname, $User.firstname
            Path                  = $User.ou  # This field refers to the OU the user account is to be created in
            EmailAddress          = $User.email
            AccountPassword       = (ConvertTo-SecureString $User.password -AsPlainText -Force) 
            Enabled               = $true
            ChangePasswordAtLogon = $false
            PasswordNeverExpires  = $true
        }

        New-ADUser @userProps

        # add the new user to the groups here
        foreach ($group in $groups) {
            Add-ADGroupMember -Identity $group -Members $username
        }
    }
}

请注意, Add-ADGroupMember 可以在-成员参数中使用用户名数组来批量添加用户,但是在这种情况下,我不建议这样做,以避免当用户已经存在于AD中时出现错误消息(因此您没有在上面的代码中创建它们)

Note that the Add-ADGroupMember can take an array of usernames in the -Members parameter to add users in bulk, but in this case I would not advice doing that to avoid error messages when users are already present in AD (so you did not create them in the code above)