S
S
Steve Road2020-01-28 07:49:46
PowerShell
Steve Road, 2020-01-28 07:49:46

How to change the Name that is displayed in AD via PowerShell?

There is a script for adding, deleting and changing users (yes, it’s possible that it’s a crooked one, since it has experienced a lot)
when updating data, it updates everything normally, except for the name itself in AD (DisplayName).

The code
import-module activedirectory
$pathToCSV="C:\script\1.csv"
$OU='ou=проверка2,ou=проверка,DC=tester,DC=local'
$domain="@tester.local"
#импортируем csv файл в переменную
$csv=import-Csv $pathToCSV -Encoding OEM -Delimiter ';'
#разбираем переменную 
foreach ($user in $csv)
  {
    #заносим в переменные значения из csv файла
    $surname="$($user.фамилия)"
    $name="$($user.имя)"
    $sname="$($user.отчество)"
    $displayname="$($user.'выводимое имя')"
    $defpass="$($user.пароль)"
    $dolzhnost="$($user.должность)"
    $depart="$($user.отдел)"
    $description="$($user.описание)"
    $room="$($user.'номер комнаты')"
    $phone="$($user.'номер телефона')"
    $mail="$($user.'электронная почта')"
    $id=$($user.'идентификатор')
    #########

    #########
    for ($i=1; $i -lt $name.length; $i++) 
    {
      #заносим логин из csv файла
      $userName="$($user.логин)"
      try 
      {
        #проеряем, есть ли пользователь
        $user=Get-ADUser "$userName"
      }
      catch 
      {
        $user=$false
      }
      #если пользователь существует
      if ($user)
      {
        #получаем id из AD
        $IDinAD=Get-ADUser $userName -Properties comment | select comment | ft -HideTableHeaders | out-string
        #если номер id из AD совпал с номером из csv
        if ($IDinAD -match $id)
        {
          #если запутили скрипт без аргументов
          if ($args[0] -eq "" -or !$args[0] )
          {
            #обновляем данные пользователя
            Set-ADUser -Identity "$userName" -Surname "$surname" -DisplayName "$displayname" `
            -OfficePhone "$phone" -EmailAddress "$mail" -Department "$depart" -Title "$dolzhnost" `
            -UserPrincipalName "$userName$domain" -GivenName "$name $sname" -Description "$description" -Office "$room" -enabled $true -SamAccountName "$userName" 
            #прерываем цикл
            break
          }
          #если запустили скрипт с аргументом -del
          if ($args[0] -eq "-del")
          {
            #удаляем пользователя
             Remove-ADUser -Identity $userName -Confirm:$false
          }
        }
        #если id не совпадают, и найдено имя пользователя, идем к следующему шагу цикла
        else
        {
          
        }
      }
      #если пользователя не существует
      else
      {
        #и запустили без аргументов
        if ($args[0] -eq "" -or !$args[0])
        {
          try 
          {
            $users=get-aduser -Filter "*" -Properties comment | select comment, name 
          }
          catch
          {
            $users=$false
          }
          if ($users)
          {
            foreach ($user in $users)
            {
              #если у какого то пользователя есть id из csv, обновляем его
              if ($user.comment -match $id)
              {
                $uname=$user.name.toString()
                $distName=Get-ADObject -Filter 'name -eq $uname'
                Set-ADUser -Identity "$uname" -Surname "$surname" -DisplayName "$displayname" `
                -OfficePhone "$phone" -EmailAddress "$mail" -Department "$depart" -Title "$dolzhnost" `
                -UserPrincipalName "$userName$domain" -GivenName "$name $sname" -Description "$description" -Office "$room" -enabled $true `
                -SamAccountName "$userName"
                Rename-ADObject $distName.DistinguishedName -NewName $displayname
              }
            }
          } 
            try
            {
            #добавляем пользователя и прерываем цикл
            New-ADUser `
            -Confirm:$false `
            -Path $OU `
            -Name "$displayname" -Surname "$surname" -DisplayName "$displayname" `
            -OfficePhone "$phone" -EmailAddress "$mail" -Department "$depart" -Title "$dolzhnost" `
            -UserPrincipalName "$userName$domain" -GivenName "$name $sname" -Description "$description" -Office "$room" -OtherAttributes @{comment="$id"} `
            -AccountPassword (ConvertTo-SecureString -AsPlainText "$defpass" -force) -enabled $true `
            -ChangePasswordAtLogon $true -SamAccountName "$userName" -erroraction 'silentlycontinue'
            }
            catch 
            {
            }
            break
        }
      }
    }
  }


Rename-ADObject $distName.DistinguishedName -NewName $displayname Seems like it should work, doesn't it?
Can you please tell me where I made a mistake?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2020-01-28
@SteveRoad

Rename-ADObject changes the CN attribute - that is, what is displayed in the list
Respectively and DistinguishedName
and DisplayName (Display name) is set to Set-ADUser -DisplayName
If you just need a Name, then this is GivenName
DistinguishedName : CN=Cheburakin Gennady Shapoklyakovich,OU=SOME_OU ,DC=forma,DC=com
CN : Cheburakin Gennady Shapoklyakovich
DisplayName : Cheburakin Gennady Shapoklyakovich
Name : Cheburakin Gennady Shapoklyakovich
Surname : Cheburakin
GivenName : Gennady

A
azarij, 2020-01-28
@azarij

I don't have anything to check against right now, but I don't see the point of the Rename-ADObject $distName.DistinguishedName -NewName $displayname line in this script yet. this cmdlet is clearly not intended to assign a displayname to a user. set-aduser should do this, but I understand it doesn't. in what way does it not? mistakes?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question