【问题标题】:Creating new AD users and adding them to multiple groups from CSV创建新的 AD 用户并将其从 CSV 添加到多个组
【发布时间】:2019-01-28 10:50:35
【问题描述】:

我的任务是创建一所学校的用户价值(英国中学)。 PS从CSV创建用户,我需要做的是将新创建的用户同时添加到各个组。

我使用的代码如下

$DCName = '<DC FQDN>'

Import-Csv -Path "D:\Import.csv" |

ForEach-Object {
    $Displayname = $_.'FirstName' + " " + $_.'LastName'
    $UPN = $_.'UPN'
    $GroupName = $_.'GroupName'
    $Prop = @{
        Name = $Displayname
        DisplayName = $_.'FirstName' + " " + $_.'LastName'
        GivenName = $_.'FirstName' 
        Surname = $_.'LastName' 
        UserPrincipalName = $UPN 
        EmailAddress = $UPN 
        SamAccountName = $_.'SAM' 
        AccountPassword = (ConvertTo-SecureString $_.'Password' -AsPlainText -Force) 
        Enabled = $true 
        Path = $_.'OU' 
        ChangePasswordAtLogon = $false 
        Title = $_.'JobTitle' 
        StreetAddress = $_.'Street' 
        City = $_.'Town' 
        State = $_.'County'
        PostalCode = $_.'PostCode' 
        OfficePhone = $_.'Telephone' 
        Company = $_.'Company' 
        Department = $_.'Department' 
        HomeDrive = $_.'HomeDrive' 
        HomeDirectory = $_.'Home-Directory' 
        OtherAttributes = @{
            'extensionAttribute1'= $_.'ExtendedAttribute1'; 
            'extensionAttribute2'= $_.'ExtendedAttribute2'; 
            'extensionAttribute14'= $_.'ExtendedAttribute14'; 
            'extensionAttribute15'= $_.'ExtendedAttribute15'; 
            'proxyAddresses' = "SMTP:" + $UPN;} 
        Server = $DCName

        }

         New-ADUser @prop

         Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'

}

创建的用户具有正确设置的所有属性。它失败并出现以下错误

Add-ADGroupMember : Cannot find an object with identity: 'Test.User' under: 'DC=AD,DC=example,DC=uk'.
At C:\Scripts\NewUserFromCSV2.ps1:47 char:10
+          Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Test.USer:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

看起来 Add-ADGroupMember 命令找不到刚刚创建的用户,但是,如果是这种情况,我不明白为什么。

目前,我的 CSV 在“GroupName”中只有一个组,将用户添加到多个组的最佳方法是什么?例如学校全体员工、教职员工、科学教师等。

提前感谢您提供的任何帮助。

【问题讨论】:

  • 很可能是复制问题,您的 DC 尚不知道新用户。您可以通过在两个命令之间添加Start-Sleep -s 30 来添加手动延迟以实现此目的...
  • 这意味着每个用户至少需要 30 秒才能完成。有近 200 名员工和 1500 名学生 - 这意味着需要 14 多个小时才能完成。
  • 将服务器开关添加到 Add-ADGroupMember 命令帮助中吗?
  • 这是一个故障查找的建议,看看它是代码还是复制。将两个命令指向同一个服务器可以解决这个问题,但您也可以将所有负载放在单个服务器上。如果您的域设置为可以处理此问题。
  • @JamesC 你不是每天晚上都这样做,对吧?如果对于尚未启用的新 AD 域而言,这只是一次性的事情,那么 14 小时又有什么意义呢?因为如果它运行得更频繁,那么你在那里有纯文本密码有点可怕。事实上,你有这个但不设置“ChangePasswordAtLogon”仍然有点可怕。如果不是更频繁,您可以在晚上离开之前开始它。

标签: powershell active-directory


【解决方案1】:

由于它是一个批量操作,我只是将用户创建与组成员身份分开。

首先创建所有用户,然后将它们添加到组中:

$DCName = '<DC FQDN>'
$Users = Import-Csv -Path "D:\Import.csv"

$Users | ForEach-Object {
    $Displayname = $_.'FirstName' + " " + $_.'LastName'
    $UPN = $_.'UPN'

    $Prop = @{
        ## properties as per original code ##
    }

    New-ADUser @prop
}

$Users | ForEach-Object {
    $GroupName = $_.'GroupName'
    Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'    
}

将用户添加到多个组:

如果您在GroupName 中有一个以分号分隔的组列表,例如

学校全员;教学人员;科学教师

Split 会将其转换为数组,然后您可以循环遍历它们:

$_.'GroupName' -split ';' | ForEach-Object {
    Add-ADGroupMember $_ –Member $user.'SAM'
}

(编辑:更新为分号,因为你有一个 csv 源)

【讨论】:

    【解决方案2】:

    我最终将它作为一个组合脚本工作,并添加了对预先存在的用户的错误检查,现有员工经常搬到新学校,该新学校在添加到我们的 AD 之前被添加到信任中并被纳入在要创建的用户列表中。

    还添加了日志文件创建以记录新创建的用户并列出其 SAMAccount 名称已存在的用户,以便我们检查用户是否需要创建或是否需要从其他 School OU 迁移。

    这是我的最终代码:

    #Get deafult variables to tidy up created variables at the end
    $ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name
    
    #New User Code Starts Here>
    
    #Variables not set by CSV
    
    #Set DC name to update - prevents errors due to replication delay
    $DCName = '<DC FQDN>'
    
    #Create log files
    "Users Exist in AD" | Out-File -FilePath "D:\Logs\ExistingUsers-$(get-date -f yyyyMMdd).txt" -Append
    "New Users Created" | Out-File -FilePath "D:\Logs\NewUsers-$(get-date -f yyyyMMdd).txt" -Append
    
    #Specify path and file to import
    Import-Csv -Path "D:\Import.csv" |
    
    #Iterate through each row in the CSV
    ForEach-Object {
    
        #Set per object variables from fields in the CSV
        $DisplayName = $_.'FirstName' + " " + $_.'LastName'
        $UPN = $_.'UPN'
        $GroupName1 = $_.'GroupName1'
        $GroupName2 = $_.'GroupName2'
        $GroupName3 = $_.'GroupName3'
        $GroupName4 = $_.'GroupName4'
        $SAM = $_.'SAM'
        $Password = $_.'Password'
        $SAMTest = Get-ADUser -Filter {(sAMAccountName -eq $SAM)} -Server $DCName
    
        #Splatting Hash Table holds all user attribute properties set in the CSV
        $Prop = @{
            Name = $DisplayName
            DisplayName = $DisplayName
            GivenName = $_.'FirstName' 
            Surname = $_.'LastName' 
            UserPrincipalName = $UPN 
            EmailAddress = $UPN 
            SamAccountName = $_.'SAM' 
            AccountPassword = (ConvertTo-SecureString $_.'Password' -AsPlainText -Force) 
            Enabled = $true 
            Path = $_.'OU' 
            ChangePasswordAtLogon = $false 
            Title = $_.'JobTitle' 
            StreetAddress = $_.'Street' 
            City = $_.'Town' 
            State = $_.'County'
            PostalCode = $_.'PostCode' 
            OfficePhone = $_.'Telephone' 
            Company = $_.'Company' 
            Department = $_.'Department' 
            OtherAttributes = @{
                'extensionAttribute1'= $_.'ExtendedAttribute1'; 
                'extensionAttribute2'= $_.'ExtendedAttribute2'; 
                'extensionAttribute14'= $_.'ExtendedAttribute14'; 
                'extensionAttribute15'= $_.'ExtendedAttribute15'; 
                'proxyAddresses' = "SMTP:" + $UPN;} 
            Server = $DCName
    
            }
    
    
        #Check if SAMAccount name exists in AD and skip existing users
        if ($SAMTest -ne $Null)
            {
            #Get UPN property of the pre-existing user
            $Exist = Get-ADUser -Filter {(sAMAccountName -eq $SAM)} -Properties 'userprincipalname'
    
            #write UPN value to variable
            $ExistUPN = $Exist.userprincipalname
    
            #Update log of pre-existing users
            "$DisplayName exists with email $ExistUPN" | Out-File -FilePath "D:\Logs\ExistingUsers-$(get-date -f yyyyMMdd).txt" -Append
    
            #Write to screen
            Write-Host "$DisplayName already exists in AD" -ForegroundColor Red
    
            }
        else
            {
            #Create new user with the attribute properties collected above
            New-ADUser @prop
    
            #Check if group fields in CSV were populated, if true add user to group, if false skip                  
            if ($_.'GroupName1'){Add-ADGroupMember -Identity $_.'GroupName1' -Members $_.'SAM' -Server $DCName}
    
            if ($_.'GroupName2'){Add-ADGroupMember -Identity $_.'GroupName2' -Members $_.'SAM' -Server $DCName}
    
            if ($_.'GroupName3'){Add-ADGroupMember -Identity $_.'GroupName3' -Members $_.'SAM' -Server $DCName}
    
            if ($_.'GroupName4'){Add-ADGroupMember -Identity $_.'GroupName4' -Members $_.'SAM' -Server $DCName} 
    
            #Update New user log 
            "$UPN" | Out-File -FilePath "D:\Logs\NewUsers-$(get-date -f yyyyMMdd).txt" -Append
    
            #Write to screen
            Write-Host "User $SAM created at $((Get-Date).ToString('hh:mm'))" -ForegroundColor Green
    
            }
    }
    
    #End Of New User Code
    
    #Remove variables set by script - keeps PS memory space tidy
    $NewVariables = Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$ExistingVariables -notcontains $_ -and $_ -ne "ExistingVariables"}
    if ($NewVariables)
        {
        Write-Host "Removing the following variables:`n`n$NewVariables"
        Remove-Variable $NewVariables
        }
    else
        {
        Write-Host "No new variables to remove!"
        }
    

    我使用了关于清除变量的内容,因为如果 PowerShell 会话保持打开状态并且会导致奇怪的事情发生,这些值似乎会持续存在。我还删除了主驱动器属性,因为指定的文件服务器尚未实现,但管理层现在仍然希望 AD 中的用户。

    作为参考,我的 import.csv 看起来像这样

    名字、姓氏、UPN、SAM、密码、OU、职位、街道、城镇、县、邮政编码、电话、公司、部门、ExtendedAttribute1、ExtendedAttribute2、ExtendedAttribute14、ExtendedAttribute15、GroupName1、GroupName2、GroupName3、GroupName4 Test,User,Test.Users@domain.uk,Test.User,,"OU=Admin Staff,OU=User Resources,OU=School,OU=Trust Schools,DC=AD,DC=Trust,DC=org", ,Street Name,TownName,County,AA11 1AA,116123,Name Of School,Name of Trust,,Staff,,,AllStaffGroup,AdminStaffGroup,SpecialPermissionsGroup,Group4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多