Solved

How to set values to AD User Properties with Powershell

Posted on 2012-12-28
43
2,389 Views
Last Modified: 2013-01-02
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
Comment
Question by:namerg
  • 21
  • 14
  • 7
  • +1
43 Comments
 
LVL 12

Expert Comment

by:Julian123
Comment Utility
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
 
LVL 39

Expert Comment

by:footech
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
@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
 
LVL 39

Expert Comment

by:footech
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
@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
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 400 total points
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 39

Expert Comment

by:footech
Comment Utility
Edit - nevermind.  I see Subsun made the suggestion while I was typing.
0
 

Author Comment

by:namerg
Comment Utility
@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
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 400 total points
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
Perfect.
0
 

Author Comment

by:namerg
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Try with..   Get-ADUser $User | Set-ADUser -surname $InputLastName -ErrorAction SilentlyContinue  -E ......
0
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
And about $AD_User = ?
Is it collected by $AD_User = Get-ADUser?
0
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 400 total points
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
$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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
I got it from your previous comments.. see my previous comment..
0
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
So you want to change display name too, Try
Set-ADUser -surname $InputLastName -DisplayName $($InputLastName+","+$AD_USER.givenName)

Open in new window

0
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
Well, the fact we are changing the lastname interactively, it makes sense through the code silently changing the display name, right ?

Thanks,
0
 
LVL 39

Expert Comment

by:footech
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
@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
 
LVL 39

Expert Comment

by:footech
Comment Utility
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
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 400 total points
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
@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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
Confused.. Are you trying to change object name or the object DisplayName?
0
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 39

Expert Comment

by:footech
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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
 
LVL 39

Accepted Solution

by:
footech earned 100 total points
Comment Utility
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
 

Author Comment

by:namerg
Comment Utility
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

In this article, we will see the basic design consideration while designing a Multi-tenant web application in a simple manner. Though, many frameworks are available in the market to develop a multi - tenant application, but do they provide data, cod…
A procedure for exporting installed hotfix details of remote computers using powershell
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

5 Experts available now in Live!

Get 1:1 Help Now