我无法使用给定和创建的属性与 New-ADUser 一起使用

发布于 2025-01-19 02:02:27 字数 1883 浏览 0 评论 0原文

我正在处理从一个域中提取的一系列广告用户数据,以重新创建另一个域。我创建了一个哈希表,将新顾问参数与从CSV导入的用户数据(由我打算重新创建的域填充)。当我用哈希表调用新顾问时,没有创建用户,也没有错误。

这是哈希表:

$NewUserAttr = @{
    'Name'              = $ADUser.UsersName
    'SamAccountName'    = $ADUser.UsersSamAccountName
    'Company'           = $ADUser.UsersCompany
    'Department'        = $ADUser.UsersDepartment
    'DisplayName'       = $ADUser.UsersDisplayName
    'EmailAddress'      = $ADUser.UsersMail
    'EmployeeID'        = $ADUser.UsersEmployeeID
    'Enabled'           = $UsersEnabled
    'GivenName'         = $ADUser.UsersGivenName
    'Initials'          = $ADUser.UsersInitials
    'Manager'           = $ADUser.Manager
    'MobilePhone'       = $ADUser.UsersMobileNum
    'OfficePhone'       = $ADUser.UsersTelephoneNumber
    'PostalCode'        = $ADUser.UsersPostalCode
    'State'             = $ADUser.UsersST
    'StreetAddress'     = $ADUser.UsersStreetAddress
    'Surname'           = $ADUser.UsersSN
    'Title'             = $ADUser.UsersTitle
    'userPrincipalname' = $ADUser.UsersUPN
    'Path'              = $ParentOU
    'Server'            = $TargetDomain

    'OtherAttr' = @{
        'c'                  = $ADUser.Usersc
        'GIDNumber'          = $ADUser.UsersGIDNumber
        'l'                  = $ADUser.UsersL
        'LoginShell'         = $ADUser.UsersLoginShell
        'msSFU30Name'        = $ADUser.UsersMsSFU30Name
        'msSFU30NisDomain'   = $ADUser.UsersMsSFU30NisDomain
        'PhysicalDeliveryOfficeName' = $ADUser.UsersPhysicalDeliveryOfficeName
        'SSN'                = $ADUser.UsersSSN
        'Uid'                = $ADUser.UsersUid
        'uidNumber'          = $ADUser.UsersUidNum
        'unixHomeDirectory'  = $ADUser.UsersUHD
    }
}

PS > New-ADUser @NewUserAttr

我将newuserattr的名称,samaccountname,path和server命名为newuserattr,这确实创建了用户,但这远远少于我所需的参数。

I am processing an array of AD User data pulled from one domain to recreate in another. I have created a hash table linking the New-ADUser parameters with the user data imported from a CSV (populated from the domain I intend to recreate). When I call New-ADUser with the hash table, the user is not created and there are no error.

Here is the hash table:

$NewUserAttr = @{
    'Name'              = $ADUser.UsersName
    'SamAccountName'    = $ADUser.UsersSamAccountName
    'Company'           = $ADUser.UsersCompany
    'Department'        = $ADUser.UsersDepartment
    'DisplayName'       = $ADUser.UsersDisplayName
    'EmailAddress'      = $ADUser.UsersMail
    'EmployeeID'        = $ADUser.UsersEmployeeID
    'Enabled'           = $UsersEnabled
    'GivenName'         = $ADUser.UsersGivenName
    'Initials'          = $ADUser.UsersInitials
    'Manager'           = $ADUser.Manager
    'MobilePhone'       = $ADUser.UsersMobileNum
    'OfficePhone'       = $ADUser.UsersTelephoneNumber
    'PostalCode'        = $ADUser.UsersPostalCode
    'State'             = $ADUser.UsersST
    'StreetAddress'     = $ADUser.UsersStreetAddress
    'Surname'           = $ADUser.UsersSN
    'Title'             = $ADUser.UsersTitle
    'userPrincipalname' = $ADUser.UsersUPN
    'Path'              = $ParentOU
    'Server'            = $TargetDomain

    'OtherAttr' = @{
        'c'                  = $ADUser.Usersc
        'GIDNumber'          = $ADUser.UsersGIDNumber
        'l'                  = $ADUser.UsersL
        'LoginShell'         = $ADUser.UsersLoginShell
        'msSFU30Name'        = $ADUser.UsersMsSFU30Name
        'msSFU30NisDomain'   = $ADUser.UsersMsSFU30NisDomain
        'PhysicalDeliveryOfficeName' = $ADUser.UsersPhysicalDeliveryOfficeName
        'SSN'                = $ADUser.UsersSSN
        'Uid'                = $ADUser.UsersUid
        'uidNumber'          = $ADUser.UsersUidNum
        'unixHomeDirectory'  = $ADUser.UsersUHD
    }
}

PS > New-ADUser @NewUserAttr

I have reduced the NewUserAttr to Name, SamAccountName, Path, and Server and that did create the user, but that is far less parameters than what I need.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吲‖鸣 2025-01-26 02:02:28

我经常使用命名的参数和空值碰到这个。要避免您的命名参数的null值,$ null指示该参数应为省略而不是提供的参数,请在创建Splat-Hashtable时遵循以下规则:

  1. 定义时标签可,定义任何不会(或不应该)的属性$ null,例如:

      $ splatargs = @{
      parameterone ='value'
      parametertwo ='其他value'
    }
     
  2. 对于可能需要或不需要根据其值提供的参数$ null(或评估falseuy),有条件地将其添加到标签:

      if($ somevar){
      $ splatargs.conditionalparameter = $ SONEVAR
    }
     

重复2。 for您有每个条件参数。另外,您可以使用所有可能的参数名称和值初始化标签,然后在检查错误后将它们剥离,与$ $ null,等。

  # You could do any condition here but in this example,
  # We will do a simple falsiness test on each key's value
  $removeParameterNames = $splatArgs.Keys | Where-Object {
    !( $splatArgs.$_ )
  }

  # Use another loop here since we don't want to modify the hashtable
  # while iterating over its keys
  foreach( $key in $removeParameterNames ) {
    $splatArgs.Remove($key)
  }

I run into this often with named parameters and null values. To avoid null values for your named parameters which $null indicates the parameter should be omitted rather than provided, follow these rules when creating the splat-hashtable:

  1. When defining the hashtable, define any properties that will not (or should not be) $null, like so:

    $splatArgs = @{
      ParameterOne = 'Value'
      ParameterTwo = 'OtherValue'
    }
    
  2. For parameters that may or may not need to be provided based on whether its value is $null (or evaluates falsey), conditionally add it to the hashtable:

    if( $someVar ) {
      $splatArgs.ConditionalParameter = $someVar
    }
    

Repeat 2. for each conditional argument you have. Alternatively, you could initialize the hashtable with all possible parameter names and values, then strip them out after after checking falsiness, comparing to $null, etc.

  # You could do any condition here but in this example,
  # We will do a simple falsiness test on each key's value
  $removeParameterNames = $splatArgs.Keys | Where-Object {
    !( $splatArgs.$_ )
  }

  # Use another loop here since we don't want to modify the hashtable
  # while iterating over its keys
  foreach( $key in $removeParameterNames ) {
    $splatArgs.Remove($key)
  }
迷你仙 2025-01-26 02:02:28

从我的评论中继续:

To avoid empty fields from being assembled in the attributes Hashtable to use for splatting, you could create two lookup tables in which you  map the CSV header names with the actual AD user attribute names.
Something like this:

    # create two mapping lookup Hashtables for 'normal' attributes and one for the OtherAttributes
    # format is: PropertyNameFromCsv = PropertyNameForActiveDirectory
    $attribMap = @{
        UsersName           = 'Name'
        UsersSamAccountName = 'SamAccountName'
        UsersCompany        = 'Company'
        Usersc              = 'Country'
        Manager             = 'Manager'
        # etc.
    }

    $otherMap = @{
        UsersGIDNumber        = 'GIDNumber'
        UsersLoginShell       = 'LoginShell'
        UsersmsSFU30Name      = 'MsSFU30Name'
        UsersmsSFU30NisDomain = 'MsSFU30NisDomain'
        # etc.
    }

接下来,导入每个条目的CSV和循环:

$csv = Import-Csv -Path 'X:\your_importFile.csv'

foreach ($item in $csv) {
    # two empty Hashtables for splatting
    $NewUserAttr = @{}
    $OtherAttr   = @{}
    # pre fill the default attributes you need for all users
    $NewUserAttr['Enabled'] = $UsersEnabled
    $NewUserAttr['Server']  = $TargetDomain
    $NewUserAttr['Path']    = $ParentOU

    # loop over the properties for each item in the CSV and only store 
    # the ones that are not empty and for which you can find a mapping
    $item.PsObject.Properties | ForEach-Object {
        if (![string]::IsNullOrWhiteSpace($_.Value)) { 
            if ($attribMap.Contains($_.Name))    { $NewUserAttr[$attribMap[$_.Name]] = $_.Value }
            elseif ($otherMap.Contains($_.Name)) { $OtherAttr[$otherMap[$_.Name]] = $_.Value }
        }
    }
    # join the hashtables together if we have OtherAttributes
    if ($OtherAttr.Count) { $NewUserAttr['OtherAttributes'] = $OtherAttr }

    # now try and create the new user
    try {
        New-ADUser @NewUserAttr -ErrorAction Stop
    }
    catch {
        Write-Warning "Error creating user $($NewUserAttr.Name): $($_.Exception.Message)"
    }
}

Continuing from my comments:

To avoid empty fields from being assembled in the attributes Hashtable to use for splatting, you could create two lookup tables in which you  map the CSV header names with the actual AD user attribute names.
Something like this:

    # create two mapping lookup Hashtables for 'normal' attributes and one for the OtherAttributes
    # format is: PropertyNameFromCsv = PropertyNameForActiveDirectory
    $attribMap = @{
        UsersName           = 'Name'
        UsersSamAccountName = 'SamAccountName'
        UsersCompany        = 'Company'
        Usersc              = 'Country'
        Manager             = 'Manager'
        # etc.
    }

    $otherMap = @{
        UsersGIDNumber        = 'GIDNumber'
        UsersLoginShell       = 'LoginShell'
        UsersmsSFU30Name      = 'MsSFU30Name'
        UsersmsSFU30NisDomain = 'MsSFU30NisDomain'
        # etc.
    }

Next, import the CSV and loop over each entry:

$csv = Import-Csv -Path 'X:\your_importFile.csv'

foreach ($item in $csv) {
    # two empty Hashtables for splatting
    $NewUserAttr = @{}
    $OtherAttr   = @{}
    # pre fill the default attributes you need for all users
    $NewUserAttr['Enabled'] = $UsersEnabled
    $NewUserAttr['Server']  = $TargetDomain
    $NewUserAttr['Path']    = $ParentOU

    # loop over the properties for each item in the CSV and only store 
    # the ones that are not empty and for which you can find a mapping
    $item.PsObject.Properties | ForEach-Object {
        if (![string]::IsNullOrWhiteSpace($_.Value)) { 
            if ($attribMap.Contains($_.Name))    { $NewUserAttr[$attribMap[$_.Name]] = $_.Value }
            elseif ($otherMap.Contains($_.Name)) { $OtherAttr[$otherMap[$_.Name]] = $_.Value }
        }
    }
    # join the hashtables together if we have OtherAttributes
    if ($OtherAttr.Count) { $NewUserAttr['OtherAttributes'] = $OtherAttr }

    # now try and create the new user
    try {
        New-ADUser @NewUserAttr -ErrorAction Stop
    }
    catch {
        Write-Warning "Error creating user $($NewUserAttr.Name): $($_.Exception.Message)"
    }
}
疯了 2025-01-26 02:02:28

这是我最终开始工作的内容,这与本德推荐的内容以及我上面评论中链接中理查德推荐的内容非常相似。

$NewUserAttr = @{
    'Name'                  = $ADUser.UsersName
    'SamAccountName'        = $ADUser.UsersSamAccountName
    'AccountPassword'       = (ConvertTo-SecureString -AsPlainText "<Ab@1Cd!2>" -Force)
    'Company'               = $ADUser.UsersCompany
    'Department'            = $ADUser.UsersDepartment
    'DisplayName'           = $ADUser.UsersDisplayName
    'EmailAddress'          = $ADUser.UsersMail 
    'EmployeeID'            = $ADUser.UsersEmployeeID
    'Enabled'               = $UsersEnabled
    'GivenName'             = $ADUser.UsersGivenName
    'MobilePhone'           = $ADUser.UsersMobileNum 
    'OfficePhone'           = $ADUser.UsersTelephoneNumber 
    'SurName'               = $ADUser.UsersSN 
    'Title'                 = $ADUser.UsersTitle
    'userPrincipalname'     = $ADUser.UsersUPN
    'Path'                  = $ParentOU
    'Server'                = $TargetDomain

    'OtherAttr' = @{
        'GIDNumber'                     = $ADUser.UsersGIDNumber
        'LoginShell'                    = $ADUser.UsersLoginShell
        'msSFU30Name'                   = $ADUser.UsersMsSFU30Name
        'msSFU30NisDomain'              = $ADUser.UsersMsSFU30NisDomain
        'Uid'                           = $ADUser.UsersUid
        'uidNumber'                     = $ADUser.UsersUidNum
        'unixHomeDirectory'             = $ADUser.UsersUHD
    } 
}

# Check the uncommon attributes and add them to the hash table if not null
if($ADUser.Usersl){$NewUserAttr.add('City',$ADUser.Usersl)}
if($ADUser.Usersc){$NewUserAttr.add('Country',$ADUser.Usersc)}
if($ADUser.UsersInitials){$NewUserAttr.add('Initials',$ADUser.UsersInitials)}
if($ADUser.Manager){$NewUserAttr.add('Manager',$ADUser.Manager)}
if($ADUser.UsersPostalCode){$NewUserAttr.add('PostalCode',$ADUser.UsersPostalCode)}
if($ADUser.UsersST){$NewUserAttr.add('State',$ADUser.UsersST)}
if($ADUser.UsersStreetAddress){$NewUserAttr.add('StreetAddress',$ADUser.UsersStreetAddress)}
if($ADUser.physicaldeliveryofficename){$NewUserAttr.OtherAttr.add('physicaldeliveryofficename',$ADUser.physicaldeliveryofficename)}
if($ADUser.UsersSSN){$NewUserAttr.OtherAttr.add('SSN',$ADUser.UsersSSN)}

#Add new user to destination domain
try {
    $UserExists = Get-ADUser -Identity $ADUser.UsersName -Server $TargetDomain
    if ($UserExists) {
        "Exists,$($ADUser.UsersName),$ParentOU`n" | Out-File $UserCreationLog -Append -Force
    } else {
        New-ADUser @NewUserAttr -ErrorAction Continue
        #Change password
        "Added,$($ADUser.UsersSamAccountName),$($ADUser.UsersName),$ParentOU`n" | Out-File $UserCreationLog -Append -Force
    }
} catch {
    $ErrorMsg = $_.Exception.Message
    Write-Log -Message "Unable to create user, $($ADUser.UsersName): $ErrorMsg." -Severity Error -LogPath $LogFile
    Write-Log -Message "Failed users attributes: $NewUserAttr $($NewUserAttr.OtherAttr)" -Severity Error -LogPath $LogPath
}

现在我只需要测试每个建议答案,看看哪个是最快的!谢谢大家!!

Here is what I ended up getting to work, which is very similar to what Bender recommended and what Richard from the link in my above comments recommended.

$NewUserAttr = @{
    'Name'                  = $ADUser.UsersName
    'SamAccountName'        = $ADUser.UsersSamAccountName
    'AccountPassword'       = (ConvertTo-SecureString -AsPlainText "<Ab@1Cd!2>" -Force)
    'Company'               = $ADUser.UsersCompany
    'Department'            = $ADUser.UsersDepartment
    'DisplayName'           = $ADUser.UsersDisplayName
    'EmailAddress'          = $ADUser.UsersMail 
    'EmployeeID'            = $ADUser.UsersEmployeeID
    'Enabled'               = $UsersEnabled
    'GivenName'             = $ADUser.UsersGivenName
    'MobilePhone'           = $ADUser.UsersMobileNum 
    'OfficePhone'           = $ADUser.UsersTelephoneNumber 
    'SurName'               = $ADUser.UsersSN 
    'Title'                 = $ADUser.UsersTitle
    'userPrincipalname'     = $ADUser.UsersUPN
    'Path'                  = $ParentOU
    'Server'                = $TargetDomain

    'OtherAttr' = @{
        'GIDNumber'                     = $ADUser.UsersGIDNumber
        'LoginShell'                    = $ADUser.UsersLoginShell
        'msSFU30Name'                   = $ADUser.UsersMsSFU30Name
        'msSFU30NisDomain'              = $ADUser.UsersMsSFU30NisDomain
        'Uid'                           = $ADUser.UsersUid
        'uidNumber'                     = $ADUser.UsersUidNum
        'unixHomeDirectory'             = $ADUser.UsersUHD
    } 
}

# Check the uncommon attributes and add them to the hash table if not null
if($ADUser.Usersl){$NewUserAttr.add('City',$ADUser.Usersl)}
if($ADUser.Usersc){$NewUserAttr.add('Country',$ADUser.Usersc)}
if($ADUser.UsersInitials){$NewUserAttr.add('Initials',$ADUser.UsersInitials)}
if($ADUser.Manager){$NewUserAttr.add('Manager',$ADUser.Manager)}
if($ADUser.UsersPostalCode){$NewUserAttr.add('PostalCode',$ADUser.UsersPostalCode)}
if($ADUser.UsersST){$NewUserAttr.add('State',$ADUser.UsersST)}
if($ADUser.UsersStreetAddress){$NewUserAttr.add('StreetAddress',$ADUser.UsersStreetAddress)}
if($ADUser.physicaldeliveryofficename){$NewUserAttr.OtherAttr.add('physicaldeliveryofficename',$ADUser.physicaldeliveryofficename)}
if($ADUser.UsersSSN){$NewUserAttr.OtherAttr.add('SSN',$ADUser.UsersSSN)}

#Add new user to destination domain
try {
    $UserExists = Get-ADUser -Identity $ADUser.UsersName -Server $TargetDomain
    if ($UserExists) {
        "Exists,$($ADUser.UsersName),$ParentOU`n" | Out-File $UserCreationLog -Append -Force
    } else {
        New-ADUser @NewUserAttr -ErrorAction Continue
        #Change password
        "Added,$($ADUser.UsersSamAccountName),$($ADUser.UsersName),$ParentOU`n" | Out-File $UserCreationLog -Append -Force
    }
} catch {
    $ErrorMsg = $_.Exception.Message
    Write-Log -Message "Unable to create user, $($ADUser.UsersName): $ErrorMsg." -Severity Error -LogPath $LogFile
    Write-Log -Message "Failed users attributes: $NewUserAttr $($NewUserAttr.OtherAttr)" -Severity Error -LogPath $LogPath
}

Now I just need to test each of these suggest answers to see which is the fastest! Thanks everyone!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文