Active Directory - Bulk - DisplayName Update -Formatting

I have a bulk project for Active Directory, to replace the DisplayName of many users. These DisplayNames may have had some value at one time. Now they just look blank. I don’t know if they are NULL or just spaces.

I am planning with this CSV file. Column Header: GoodSamAcct, Only one column:




I want the DisplayName to look like this:

Ripper, Jack - (Health)

I have developed a format that gives good results:

PS C:\> $firstname = 'Jack'

$lastname = 'Ripper'

$department = 'Health'

[string]::Concat($lastname,', ',$firstname,' - (',$department,')')

Ripper, Jack - (Health)

PS C:\>

And I have come up with this script:

$users = Import-csv c:\docs\BulkUsers.csv

Foreach ($user in $Users) {

Set-ADUser -Identity $user.GoodSamAcct -DisplayName ("$[string]::Concat($lastname,', ',$firstname,' - (',$department,')')")

  1. I tried to transfer the format that works on the console – to the script. Did I tranfer it correctly? And will this format work with the Foreach statement?
  2. I would also like the script to choose this format or another one by testing the state. If the state is Kansas, for example, execute one part , If not Kansas, execute the other nearly identical part. It seems like a simple if statement; If state contains Kansas test. But I don’t know how to set it up.
  3. Or maybe we need to
      -Clear DisplayName
  -Add @{              }</pre>


Because there may have been some data in Display name previously.

Am I on the right track?

If the sAMAccountNames in your CSV file always follow the naming convention "FirstName.Surname" you can use the -split operator to split this sAMAccountname into its components like this:
$SplittedGoodSamAcct = 'Jack.Ripper' -split '\.'

Olaf, thanks for your reply. I must practice this on the console to see how -split works. And I will keep this in mind. Yes, we have standards and naming conventions but - Nothing is 100% around here, so just to be sure I will run a one-liner for all these users to look at the critical properties. Judging from past experience, I expect 98% compliance to the naming conventions.

But I am mostly concerned with whether or not the formatting that works on the console will work with the ForEach statement that I tried to write.

I am worried that there must be some other format that must be used along with the ForEach statement.



If this is not the perfect opportunity to correct all non compliant accounts first. :wink: :smiley:

Why should something work differently when you run it inside a script or a script block to the console?

Why? And you don’t have to run the code without testing it in advance. Depending on the amount of accounts you could simply output it to the console in a table format before you run the code to change the AD.


Try the following snippet … it won’t do anything else than outputting results to the console.

$userList = Import-Csv -Path c:\docs\BulkUsers.csv
Foreach ($userName in $UserList) {
    $ADUser = Get-ADUser -Identity $userName.GoodSamAcct -Properties Department
        CSVuserName = $ADUser.sAMAccountName
        FirstName   = ($ADUser.sAMAccountName -split '.')[0]
        SurName     = ($ADUser.sAMAccountName -split '.')[1]
        DisplayName = '{0}, {1} - ({2})' -f ($ADUser.sAMAccountName -split '.')[1], ($ADUser.sAMAccountName -split '.')[0], $ADUser.Department

Olaf, Thank you for your reply.

You said: “Why should something work differently when you run it inside a script or a script block to the console?”

This is the part I am worried about, Did I assemble it correctly? -Are the $ and ’ and ) and ,’)’)") correctly assembled?

Splitting the Names is something I will try sometime, although I am not worried about how to do that right now.

-DisplayName ("$[string]::Concat($lastname,', ',$firstname,' - (',$department,')')")

Your suggestion to try it on the console is an eye-opener for me. I will try putting my code in there, similar to yours. So that:

It will still use the CSV file – For each SamAccountName – Create a custom object, [PSCustomObject] – Assemble it in a HashTable –

And then I guess, it will display the formatted results on the console.

Alright, But I don’t know when I will get to it. The boss is not very understanding about developing PowerShell. But if I can get this to work with 800 users, he may take notice.

Thanks Olaf!



To be honest - I don’t know, sorry. :wink: I extended my code suggestion above to query the AD for the user account and use the department information to create a new displayname. Test it.

You guess? Why don’t you try it? It takes only seconds to copy the code from here to a console or to the ISE or VSCode and run it.

Tell him (or here) you will save him (or her) several thousand dollars by accomplishing task in a fraction of the time by using Powershell to automate recurring tasks. Usually bosses only understand financial arguments - not technical. :wink:

I tried my code on some dummy records and wiped out the DisplayNames with Gibberish.

It is as I suspected.

My testing on the console does well:

PS C:\&gt; $firstname = 'Jack'
$lastname = 'Ripper'
$department = 'Health'
[string]::Concat($lastname,', ',$firstname,' - (',$department,')')
Ripper, Jack - (Health)

But trying to transfer it to this does not work:

-DisplayName ("$[string]::Concat($lastname,', ',$firstname,' - (',$department,')')")

And why don’t you try my code suggestion??? Again … it takes seconds to copy that snippet to a console and there is no “set” or “write” cmdlet involved. So no danger to destroy anything.

[quote quote=293754]I tried my code on some dummy records and wiped out the DisplayNames with Gibberish.

It is as I suspected.

My testing on the console does well:

<textarea class="urvanov-syntax-highlighter-plain print-no" style="tab-size: 4; font-size: 14px !important; line-height: 18px !important; z-index: 0; opacity: 0;" readonly="readonly" data-settings="dblclick">PS C:\&amp;gt; $firstname = 'Jack' $lastname = 'Ripper' $department = 'Health' [string]::Concat($lastname,', ',$firstname,' - (',$department,')') Ripper, Jack - (Health) PS C:</textarea>
PS C:\&amp;gt; $firstname = 'Jack'
$lastname = 'Ripper'
$department = 'Health'
[string]::Concat($lastname,', ',$firstname,' - (',$department,')')
Ripper, Jack - (Health)
But trying to transfer it to this does not work:
<textarea class="urvanov-syntax-highlighter-plain print-no" style="tab-size: 4; font-size: 14px !important; line-height: 18px !important; z-index: 0; opacity: 0;" readonly="readonly" data-settings="dblclick">-DisplayName ("$[string]::Concat($lastname,', ',$firstname,' - (',$department,')')")</textarea>
-DisplayName ("$[string]::Concat($lastname,', ',$firstname,' - (',$department,')')")
$Allusers = Import-csv C:\Users\Administrator\Desktop\data.csv

Foreach ($user in $AllUsers) {
$Userinfo=Get-ADUser -Identity $user.GoodSamAcct -Properties department,state
$NewDispalyName=[string]::Concat($lastname,’, ‘,$firstname,’ - (’,$department,’)’)
$InKansasDisplayName=[string]::Concat($lastname,’, ‘,$firstname,’ – (’,$department,’)–’) #I added extra –

if ($Userinfo.State -eq "Kansas"){Set-ADUser -Identity $user.GoodSamAcct -DisplayName $InKansasDisplayName}
     Set-ADUser -Identity $user.GoodSamAcct -DisplayName $NewDispalyName

Get-ADUser -Identity $user.GoodSamAcct -Properties department,state,displayname | ft department,state,displayname


I try to make it simpler so its clear, I tested this code on my test env and the code work as expected.

If the user in Kansas, the user will have a different result, (Extra – are added)

Also, try my code or Olaf code in small test users with a limited scope.

It’s also possible to not do any change more than logging the change on a text file or any output so you feel safe about the change.


you can add a -whatif on each of your set-aduser commands to validate the user you expect would be returned, and since you have your strings in the variables, inside of your foreach you could do something like $newdisplay|out-file output.txt -append

then you’re the logic itself, but not making any actual changes, review your output file to see the values that were built via your concats

Faris, Many Thanks. I am making real progress. Still working on it. Working long hours at my job. I will reply more this weekend.
I have real hope again.
Thank you, Olaf.

I ask again - did you try my code suggestion? It could be a starting point for further steps.

Olaf, Yes, indeed. Your Split is in the code right now. It is working great. I did not know how to put it to good use. But now I do. You will see, I will write more this weekend.

1 Like

Great that it helped and thanks for the feedback. :slight_smile:

I have spent long hours getting this little script working. Many thanks to Olaf and Faris for getting me started. I did not know how to collect several properties and put them all back into one property so it could be written to, or Set, (Set-ADUser)
Everything below is sanitzed using obvious identical letters. JJJ ZZZ SSS etc.,
In this script I changed the DisplayName, combining samaccountname, l , Department, state
The Script removes the characters “JJJ” from the Department, if present.
And if extensionAttribute8 equals “Contractor” It inserts “(CTR)” after the last name.

And it took a long time to figure out how to take out a few characters of a Variable:

$department = $department -replace “JJJJ-“, “”

CVS File:

Here’s what some of the properties look like for Lizzie and Jack before the script ran.

PS C:\windows\system32> Import-Csv -Path "C:\homeuse\Bulkusers2.csv" |           
foreach {           
 Get-ADUser -Filter "cn -like '*$($_.GoodSamAcct)*'" -Properties * | select samaccountname, displayname, name, cn, mail, givenname, initials, sn, extensionAttribute8, ZZZZAbbreviation, Department, Description, l, state, distinguishedname, streetaddress, postalcode, ZZZZofficeid, personguid           
samaccountname         : Lizzie.Borden
displayname            :
name                   : Lizzie.Borden
cn                     : Lizzie.Borden
mail                   : Lizzie.Borden@ZZZZ.www
givenname              : Lizzie
initials               :
sn                     : Borden
extensionAttribute8    : Contractor
ZZZZAbbreviation : JJJJ-SSSS
Department             : JJJJ-SSSS
Description            : Delete 02/27/2021 - RRR3925954 - JJJJ-SSSS
l                      : Twin Falls
state                  : ID
distinguishedname      : CN=Lizzie.Borden,OU=Deprovision,OU=Users,OU=JJJJ,OU=Agencies,XX=ZZZZ,XX=net
streetaddress          : 1441 FILLMORE ST
postalcode             : 83301
ZZZZofficeid           : 61056
personguid             : D6407B64-A225-4C83-85CA-A84747A630E3
samaccountname         : Jack.Ripper
displayname            :
name                   : Jack.Ripper
cn                     : Jack.Ripper
mail                   :
givenname              : Jack
initials               :
sn                     : Ripper
extensionAttribute8    : Affiliate
ZZZZAbbreviation : SSSS-CD
Department             : JJJJ-SSSS - JJJJ-SSSS-CD
Description            : Delete 02/27/2021 - RRR3926269 - SSSS-CD
l                      : Selmer
state                  : TN
distinguishedname      : CN=Jack.Ripper,OU=Deprovision,OU=Users,OU=JJJJ,OU=Agencies,XX=ZZZZ,XX=net
streetaddress          : 512 Mulberry
postalcode             : 38375
ZZZZofficeid           : 102748
personguid             : 4F2A4D20-3DF9-4F55-9B07-E9D03CCD3E28

Here is the script:

PS C:\windows\system32> Foreach ($user in $AllUsers) {
$Userinfo=Get-ADUser -Identity $user.GoodSamAcct -Properties department,state,l,extensionAttribute8
$department = $department -replace “JJJJ-“, “”
 $NewDispalyName=[string]::Concat($lastname,', ',$firstname,' - ',$department,', ',$l,', ',$state)
$InContractorDisplayName=[string]::Concat($lastname,', ',$firstname,' (CTR) - ',$department,', ',$l,', ',$state)
Write-Host $NewDispalyName
Write-Host $l
Write-Host $department
     if ($Userinfo.extensionAttribute8 -eq "Contractor"){Set-ADUser -Identity $user.GoodSamAcct -DisplayName $InContractorDisplayName}
         Set-ADUser -Identity $user.GoodSamAcct -DisplayName $NewDispalyName
Get-ADUser -Identity $user.GoodSamAcct -Properties department,state,displayname | ft department,state,displayname

This is what appears on the Console after the script runs. :

Borden, Lizzie - SSSS, Twin Falls, ID
Twin Falls
Department   state   displayname                             
----------            -----     -----------                             
JJJJ-SSSS          ID        Borden, Lizzie (CTR) - SSSS, Twin Falls, ID
Ripper, Jack - SSSS - SSSS-CD, Selmer, TN

department                       state       displayname                                
----------                               -----         -----------                                
JJJJ-SSSS - JJJJ-SSSS-CD     TN           Ripper, Jack - SSSS - SSSS-CD, Selmer, TN

PS C:\windows\system32>

1 Like

Great. Thanks for sharing. :+1: :wink:

But … could you please format your code as code? It prevends the forum software from inserting unwanted line breaks and makes the code easier readable. You can edit your existing post, select the code and hit the code formatting icon on the edit bar ( </> ).

Thanks in advacne

Olaf, late last evening I couldn’t figure out how to format it as code. I was tired. And it sure is easier to read now when it is formatted as code!

I know this script seems very easy to you, but for me it is monumental.
I can see I need to study how to add and delete text in strings and variables. What verbs should I look up and study? What topics?

Now that I have finished it and tested it, Monday morning I will run it in production, as we say.

Is this script easy and elementary? I would be interested in learning a more advanced script that does the same thing.

Fais and Olaf, Thanks again!