[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2900
  • Last Modified:

How to set values to AD User Properties with Powershell

Hello,

I am trying to change the following AD User properties



$AD_User_Change = Read-Host '1 = LASTNAME. 2 = FIRST NAME. 3 = DEPARTMENT. 4 = TITLE. 5 = TELEPHONE NUMBER. 6 = EMPLOYEE ID. 7 = EMPLOYEE NUMBER'

If 1 is chosen then

$NewLastName = Read-Host "Are you sure, you want to replace the following lastname ""$($AD_USER.sn)"" by ""$($InputLastName)"" (Y/N)"

if (($NewLastName -eq "y"))
   {
    Set-ADUser -sn "$($InputLastName)" ---> I AM STUCK HERE
Write-Host "New LastName SET"
Start-Sleep -Seconds 30
                    }
              }
Thanks for your help,
G
0
namerg
Asked:
namerg
  • 21
  • 14
  • 7
  • +1
5 Solutions
 
Julian123Commented:
Set-QADUSER is the easiest I've found. here's some background on how to use it: http://dmitrysotnikov.wordpress.com/2007/07/25/set-any-ad-attribute-with-powershell/.

Also, here's another link with similar info for background: http://poshoholic.com/2009/06/23/powershell-quick-tip-setting-ad-object-attributes-with-scriptblock-parameters/
0
 
footechCommented:
Without the actual script it's difficult to tell if something is missing unintentionally or because you just didn't mention it.

A couple notes though.
if (($NewLastName -eq "y"))   <---you only need one set of parentheses
Set-ADUser -sn "$($InputLastName)"   <---You need to specify the identity of the user you'll be modifying by specifying its distinguished name (DN), GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.  For example:
Set-ADUser JDoe -surname "$LastName"

Open in new window


Where are you planning on getting the last name from?  If you wanted to input it right there you could use
Set-ADUser JDoe -surname (Read-Host "Enter last name")

Open in new window

0
 
SubsunCommented:
I am not sure from where you are reading user name. You can use Switch command  try something like this.. let me know if you have any trouble to understand the script..
$User = Read-Host "Type the UserName"	
$AD_User_Change = Read-Host "1 = LASTNAME. 2 = FIRST NAME. 3 = DEPARTMENT. 4 = TITLE. 5 = TELEPHONE NUMBER. 6 = EMPLOYEE ID. 7 = EMPLOYEE NUMBER"

switch ($AD_User_Change)
    { 
        1 {$InputLastName = Read-Host "Type the new Last Name"							                                        
	    $NewLastName = Read-Host "Are you sure, you want to replace the following lastname $AD_USER.sn by $InputLastName (Y/N)"
		if ($NewLastName -eq "y"){
    		 Set-ADUser $User -surname $InputLastName -ErrorAction SilentlyContinue -ErrorVariable Err1
		   If($Err1.Count -eq 0){
		    Write-Host "Set new LastName $InputLastName for $user"}
		   Else{
		    Write-Host "Failed to set new LastName $InputLastName for $user"}
		}
          }					 
        2 {"Your code for FIRST NAME here"} 
        3 {"Your code for DEPARTMENT here"} 
        4 {"Your code for TITLE here"} 
        5 {"Your code for TELEPHONE NUMBER here"} 
        6 {"Your code for EMPLOYEE ID here"} 
        7 {"Your code for EMPLOYEE NUMBER here"}
        default {"Your code if none of above selected"}
    }

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
namergSystems AdministratorAuthor Commented:
Ohh boys, I do not want to change the logic of the algorithm.

@Subsun: Correct, that is how I have it, well, sort of.

My apologies in not getting back to you asap, it is weekend here, you know...

If I do not get back to you during the weekend, I will get back to you the day after tomorrow, Monday, 31st.

Cheers,
G
0
 
namergSystems AdministratorAuthor Commented:
@Subsun or whoever.

This is what my script does:

Querying Employee from file against Active Directory

++++++++++++++++++++++++++++ FOUND THE FOLLOWING EMPLOYEE IN FILE ++++++++++++++++++++++++++++
LASTNAME: lastname-user
FIRST NAME: firstname-user
DEPARTMENT: Information Services
TITLE: Sr System/NetworkAdministrator
TELEPHONE NUMBER: 303-333-3333
FLEX ID: 1111
CLOCK NUMBER: 2222
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

============================ FOUND THE FOLLOWING EMPLOYEE IN ACTIVE DIRECTORY ==========================
LASTNAME: last-name-user
FIRST NAME: firstname-user
DEPARTMENT: Information Services
TITLE: Sr System/NetworkAdministrator
TELEPHONE NUMBER: 303-333-3333
EMPLOYEE ID:
EMPLOYEE NUMBER:
==========================================================================================================

NOTE: Is this the right Employee, You are working on? (Y/N): y

NOTE: Is the EMPLOYEE Information FOUND In ACTIVE DIRECTORY CORRECT AGAINST The EMPLOYEE Information FOUND In the File? (Y/N): n

Which of the following Employee information would you like to change in Active Directory ?

1 = LASTNAME. 2 = FIRST NAME. 3 = DEPARTMENT. 4 = TITLE. 5 = TELEPHONE NUMBER. 6 = EMPLOYEE ID. 7 = EMPLOYEE NUMBER: 1
1
Type the new Last Name:: lastname-lastname-user

Are you sure, you want to replace the following lastname @{sn=lastname-user; givenName=firstname-user; department=Information Services; title=Sr System/NetworkAdministrator; telephoneNumber=303-333-3333; employeeID=; employeeNumber=}.sn by lastname-lastname-user (Y/N):

So, questions:
In the last paragraph why the resultant of @AD_USER.sn brings all the fields ?
How can I put double quotes around lastname-lastname, so it ends up like "lastname-lastname" ?

Once I figure this out, I can continue working with Set-ADUser

Thanks for your help,
G
0
 
footechCommented:
Difficult to say without the code.  Maybe someone else can look at what you've provided and know exactly what code you've used to make it...

1)  I'm thinking it could either be because of the way you're pulling in the info, or because of the syntax that you're using to try to display it.  Does the object even have a property called "sn"?
2)  Inside a string, use two double-quotes for one to appear.

I'm sorry, but you're basically asking someone to debug code or point out syntax errors without providing the source.  I'm not sure how you're going to get a good result that way.
0
 
namergSystems AdministratorAuthor Commented:
@footech:

You are right but I will do my best. Yes, there is a property called sn.

$file = Import-Csv "c:\scripts\ad\temp\file.csv" -header sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber

$ad = Get-ADUser -filter * -Properties sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber  -SearchBase "OU=ou,DC=domain,DC=com" | Select-Object sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber

#Then I do a for...

foreach ($AD_User in $ad) {
if ($file[0].sn -eq $AD_User.sn) {
 Write-Host "BINGO FOUND IT"

}
Start-Sleep -Seconds 30
}

Thanks,
0
 
SubsunCommented:
Are you sure, you want to replace the following lastname @{sn=lastname-user; givenName=firstname-user; department=Information Services; title=Sr System/NetworkAdministrator; telephoneNumber=303-333-3333; employeeID=; employeeNumber=}.sn by lastname-lastname-user (Y/N):

Are you using $($AD_User.sn) to print the detail here? if not try it.. else please post the line from script which you use to print the above information..
0
 
namergSystems AdministratorAuthor Commented:
Got it, it worked...

It produces the following:

Are you sure, you want to replace the following lastname Silveira by Silvei (Y/N):

Question: How do I put double quotes  to make it appear like this:

Are you sure, you want to replace the following lastname "Silveira" by "Silvei" (Y/N):

This is the code:
$NewLastName = Read-Host "Are you sure, you want to replace the following lastname $($AD_User.sn) by $InputLastName (Y/N)"

Thanks,
0
 
footechCommented:
Edit - nevermind.  I see Subsun made the suggestion while I was typing.
0
 
namergSystems AdministratorAuthor Commented:
@footech: That is what I have, see my post above:
 ***************This is the code:********************
$NewLastName = Read-Host "Are you sure, you want to replace the following lastname $($AD_User.sn) by $InputLastName (Y/N)"
*******************************

Thanks,
0
 
SubsunCommented:
Try
$NewLastName = Read-Host "Are you sure, you want to replace the following lastname ""$($AD_User.sn)"" by ""$InputLastName"" (Y/N)"

Open in new window

0
 
namergSystems AdministratorAuthor Commented:
Perfect.
0
 
namergSystems AdministratorAuthor Commented:
Now, let's solve this ticket with Subsun post about  Set-ADUser

if ($NewLastName -eq "y"){
                 Set-ADUser $User -surname $InputLastName -ErrorAction SilentlyContinue -ErrorVariable Err1
               If($Err1.Count -eq 0){
                Write-Host "Set new LastName $InputLastName for $user"}
               Else{
                Write-Host "Failed to set new LastName $InputLastName for $user"}
            }

Working on it....
0
 
namergSystems AdministratorAuthor Commented:
Hmm, getting the following error:


Are you sure, you want to replace the following lastname "Silveira" by "Silvei" (Y/N): y
Set-ADUser : Cannot find an object with identity: 'Hostname\ger' under: 'DC=domain,DC=com'.
At C:\scripts\AD\test.ps1:72 char:7
+                Set-ADUser $User -surname $InputLastName -ErrorAction SilentlyContinue  -E ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (hostname\ger:ADUser) [Set-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: 'UPIFTP00\ger' under: 'DC=upicolo,DC=pvt'.,Microsoft.ActiveDirectory.Management.Commands.SetADUser
0
 
SubsunCommented:
Try with..   Get-ADUser $User | Set-ADUser -surname $InputLastName -ErrorAction SilentlyContinue  -E ......
0
 
namergSystems AdministratorAuthor Commented:
Nada, i get the following:

Are you sure, you want to replace the following lastname "Silveira" by "Silvei" (Y/N): y

Get-ADUser : Cannot find an object with identity: 'hostname\ger' under: 'DC=domain,DC=com'.
At C:\scripts\AD\test.ps1:72 char:7
+                Get-ADUser $User  | Set-ADUser -surname $InputLastName -ErrorAction Silent ...
+                ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (hostname\ger:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : Cannot find an object with identity: 'hostname\ger' under: 'DC=domain,DC=com'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
0
 
SubsunCommented:
Hope hostname\ger is available in AD.. If yes.. Right now, I don't have access to system now to test.. can you input the sAMAccountName of user to $User var, instead of "hostname\ger"
0
 
namergSystems AdministratorAuthor Commented:
Well not really, hostname\ger is local account on a workgroup computer.

Why are we using $User, don't we need to use $AD_User.sn ?

Through one of our posts:

$NewLastName = Read-Host "Are you sure, you want to replace the following lastname ""$($AD_User.sn)"" by ""$InputLastName"" (Y/N)"

$AD_User.sn has the active directory lastname of the user in question.

We need to replace the lastname set on $AD_User.sn for @InputLastName.

Thanks,
0
 
SubsunCommented:
You cannot use Set-ADUser to modify local user.. you can replace $User with any var but it should point to the AD account which you are trying to modify. Set-ADUser or Get-ADUser will accept Distinguished Name, objectGUID, objectSid or sAMAccountName of the ad account as Identity input.
0
 
namergSystems AdministratorAuthor Commented:
Hmm,,I think we are not in the same page.

I am not trying to modify a local user, I want to modify/replace values for an AD user.

So, I do not quite understand the logic of using $user.

Anyway, you are the guru, so what's next ?
0
 
SubsunCommented:
Somehow the variable $user have the value hostname\ger instead of the AD account name which you are trying to modify. SO I am not sure how you are getting the user name from AD.

Logic is simple.. You need to replace the $user with the variable contain the AD account which you want to modify? So question is, in script how you are inputting the information of user account which you want to modify (Or which variable hold the information of the AD user which you trying to modify)
0
 
namergSystems AdministratorAuthor Commented:
hmm ok, i got it.
Hmm weird at the command prompt, i typed $user and I get ComputerName\ger

And, I am not using $user variable at all in the code. Although, I am using Powershell v3.

You asked: how you are inputting the information of user account which you want to modify?
Answer:.
.
.

                  $InputLastName = Read-Host 'Type the new Last Name:'
                  Write-Host ""
                  $NewLastName = Read-Host "Are you sure, you want to replace the following lastname ""$($AD_User.sn)"" by ""$InputLastName"" (Y/N)"
                  if (($NewLastName -eq "y")) {

#change the AD user last name by the information entered on $InputLastName
}

Thanks,
G
0
 
SubsunCommented:
And about $AD_User = ?
Is it collected by $AD_User = Get-ADUser?
0
 
SubsunCommented:
Ok, I got it..

Change following line to add sAMAccountName
$ad = Get-ADUser -filter * -Properties sAMAccountName,sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber  -SearchBase "OU=ou,DC=domain,DC=com" | Select-Object sAMAccountName,sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber

Open in new window

And replace $user with $AD_User.sAMAccountName
0
 
namergSystems AdministratorAuthor Commented:
$AD_User comes from a for { } statement...see below:

$file = Import-Csv "c:\scripts\ad\temp\file.csv" -header sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber

$ad = Get-ADUser -filter * -Properties sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber  -SearchBase "OU=ou,DC=domain,DC=com" | Select-Object sn,givenName,department,title,telephoneNumber,employeeID,employeeNumber
.
.
.
foreach ($AD_User in $ad) {
   If if ($file[0].sn -eq $AD_User.sn) {
Write-Host ""
            Write-Host "== FOUND THE FOLLOWING EMPLOYEE IN ACTIVE DIRECTORY ==="
            Write-Host "LASTNAME: $($AD_USER.sn)"
            Write-Host "FIRST NAME: $($AD_USER.givenName)"
            Write-Host "DEPARTMENT: $($AD_USER.department)"
            Write-Host "TITLE: $($AD_USER.title)"
            Write-Host "TELEPHONE NUMBER: $($AD_USER.telephoneNumber)"
            Write-Host "EMPLOYEE ID: $($AD_USER.employeeID)"
            Write-Host "EMPLOYEE NUMBER: $($AD_USER.employeeNumber)"  

               $YesNo = Read-Host 'NOTE: Is the EMPLOYEE Information FOUND In ACTIVE DIRECTORY CORRECT AGAINST The EMPLOYEE Information FOUND In the FILE? (Y/N)'
            Write-Host ""
            #Write-Host "YesNo Value: $($YesNo)"
            if (($RightWrong -eq "Y") -and ($YesNo -eq "N"))
               {
                        Write-Host "Which of the following Employee information would you like to change in Active Directory ?"
                        Write-Host ""
                        $AD_User_Change = Read-Host '1 = LASTNAME. 2 = FIRST NAME. 3 = DEPARTMENT. 4 = TITLE. 5 = TELEPHONE NUMBER. 6 = EMPLOYEE ID. 7 = EMPLOYEE NUMBER'
                  }

switch ($AD_User_Change) {
             1 {
                  Write-Host "1"
                  $InputLastName = Read-Host 'Type the new Last Name:'
                  Write-Host ""
                  $NewLastName = Read-Host "Are you sure, you want to replace the following lastname ""$($AD_User.sn)"" by ""$InputLastName"" (Y/N)"
                  if (($NewLastName -eq "y"))
                     {
                     # *******I AM STUCK HERE****************
                     Get-ADUser $User  | Set-ADUser -surname $InputLastName -ErrorAction SilentlyContinue -ErrorVariable Err1
                      #Set-ADUser -sn "$($InputLastName)"
                        Write-Host "New LastName SET"
                        Start-Sleep -Seconds 30
                    }
                }
}
}
}

I hope it helps.... thanks,
0
 
SubsunCommented:
I got it from your previous comments.. see my previous comment..
0
 
namergSystems AdministratorAuthor Commented:
Almost there, :)

It did change it. Thank you very much.

But, looking through AD, I see the name column as the oldlastname,firstname which is the
"Display name" when you right click and do properties.

Then we will be all set. :)
0
 
SubsunCommented:
So you want to change display name too, Try
Set-ADUser -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName)

Open in new window

0
 
namergSystems AdministratorAuthor Commented:
Hmm, got this:

Are you sure, you want to replace the following lastname "Silveira" by "Silvei" (Y/N): y

cmdlet Set-ADUser at command pipeline position 1
Supply values for the following parameters:
0
 
SubsunCommented:
I didn't get you.. Do you want a prompt for display name change too? of you just want to add it to same question?
0
 
namergSystems AdministratorAuthor Commented:
Well, the fact we are changing the lastname interactively, it makes sense through the code silently changing the display name, right ?

Thanks,
0
 
footechCommented:
For your last error, assuming you're using the code copied directly from Subsun's example, same issue you had before, you need to specify which identity to apply it to.  i.e.
Set-ADUser $AD_User.sAMAccountName -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName)

Open in new window

Note that you'll also want to update the displayname if you change the firstname, so just use the same principle as used here, but the code bit would be like -DisplayName $($InputFirstName+","+$AD_USER.surName).
0
 
namergSystems AdministratorAuthor Commented:
@footech: what do you mean with identity ?

This is the code:
# **************I AM STUCK HERE****************************
Get-ADUser $AD_User.sAMAccountName  | Set-ADUser -surname $InputLastName -ErrorAction SilentlyContinue -ErrorVariable Err1 #***--> This one works
Start-Sleep -Seconds 5
Set-ADUser -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName)

Thanks,
0
 
footechCommented:
Look at the difference between
Set-ADUser -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName)

Open in new window

and
Set-ADUser $AD_User.sAMAccountName -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName)

Open in new window


In this example:
Get-ADUser $AD_User.sAMAccountName  | Set-ADUser -surname $InputLastName -ErrorAction SilentlyContinue -ErrorVariable Err1

Open in new window

the identity for the Set-ADUser command is being supplied from the pipeline from Get-ADUser.
0
 
SubsunCommented:
Well, the fact we are changing the lastname interactively, it makes sense through the code silently changing the display name, right ?
Yes, that would be fine..

For the change, The code should be (Change Last name and display name in same line)
Get-ADUser $AD_User.sAMAccountName  | Set-ADUser -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName) -ErrorAction SilentlyContinue -ErrorVariable Err1
Start-Sleep -Seconds 5

Open in new window

or
Set-ADUser $AD_User.sAMAccountName -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName) -ErrorAction SilentlyContinue -ErrorVariable Err1
Start-Sleep -Seconds 5

Open in new window

0
 
namergSystems AdministratorAuthor Commented:
@subsun: It did it through properties but not through the display under the Name column, see attachment.

I will try to get back on this tomorrow from home. Otherwise on Wednesday.

Thank you subsun, footech and all Experts-Exchange. I wish you a happy new year 2013. I am living early from work at this moment...

cheers,
Capture.PNG
0
 
SubsunCommented:
Confused.. Are you trying to change object name or the object DisplayName?
0
 
namergSystems AdministratorAuthor Commented:
I'm back.

Subsun, when you open Active Directory Users and Computers you see three columns: Name, Type and Description, right ? and they reflect all AD users, right ?

So, when you right click on a user, you will see the AD User Properties window, right ?

The Display name property changed but did not change the name value under the ADUC, do you understand me ?

Thanks for your help,
0
 
footechCommented:
Those are different properties.  I'm pretty certain that it's the CN attribute that is being shown there.  I'd have to search to find how to change it though.
0
 
namergSystems AdministratorAuthor Commented:
Thanks footech,
I am working on this piece

$NewDN = $InputLastName+", "+$AD_USER.givenName
Rename-ADObject -identity $AD_User -Newname $newDN

But, I get an error....
0
 
footechCommented:
As it looks like you've discovered, the Rename-ADObject is the way to do this.  The identity supplied to the cmdlet has to be either a DN or GUID.  Easiest way will probably be
Get-ADUser $AD_User.sAMAccountName  | Rename-ADObject -newname $newDN

Open in new window

(BTW, a suggestion - it might be confusing that $newDN doesn't actually specify a DN, so a different variable name might be in order).
0
 
namergSystems AdministratorAuthor Commented:
It worked . Perfect.

I was going to user $NewName but not sure if will conflict witn -newname

What do you think ?

Nevermind, just tested it and worked fine. Closing this question.

Subsun and Footech thank you very much.

For sure you will see more questions from me.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 21
  • 14
  • 7
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now