question

VictorFlorncio-1904 avatar image
0 Votes"
VictorFlorncio-1904 asked dawsayan commented

Powershell - Help to fill AD Attributes for users from CSV

Hi everyone,

Today we received a CSV with 2k users to change their AD Attributes.

Something like that:

53269-image.png


The CSV was already exported and I need to import those informations to their Attributes.

I Tried some scripts but, none of them worked.

Does anybody here has an basic idea of a script that could help me?

Scripts that already tried:

Import-Module ActiveDirectory

$USERS = Import-CSV ""

$USERS|Foreach{
Get-ADUser -filter {name -eq $.name}|Set-ADUSer -MobilePhone $.MobilePhone -StreetAddress $.StreetAddress -City $.City -Title $_.Title}

And

Import-module ActiveDirectory
$users = Import-Csv "C:\ad_import\users.csv"
foreach ($user in $users) {
$props = @{
identity = $user.samaccountname
givenName = if($user.FirstName ){$user.FirstName }else{$null}
surname = if($user.LastName ){$user.LastName }else{$null}
title = if($user.JobTitle ){$user.JobTitle }else{$null}
description = if($user.description){$user.description}else{$null}
state = if($user.State ){$user.State }else{$null}
Office = if($user.Office ){$user.Office }else{$null}
department = if($user.Department ){$user.Department }else{$null}
city = if($user.City ){$user.City }else{$null}
manager = if($user.manager ){$user.manager }else{$null}
company = if($user.company ){$user.company }else{$null}
}
set-aduser @props
}

The structure of CSV is:

53362-image.png


windows-server-powershellwindows-active-directory
image.png (6.9 KiB)
image.png (9.5 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Since none of the scripts worked, please let us know how it didn't work. Did you see any error messages?

0 Votes 0 ·
RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered RichMatheisen-8856 edited

In your first example, the only place that has an underbar after the "$" is in the "-Title $<underbar>.Title" parameter. All the other parameter values use only "$.valuename" where they should use "$<underbar>.valuename". However that may be due to the way Microsoft's Q&A editor works! Try using the "Code Sample" icon in the formatting bar when posting code. It's not perfect, but it does eliminate a lot of problems posting code.

Also, in the first example's "Get-ADUser" you're using the "name" value from the CSV in the -Filter. If the filter fails to find that value the result is $null -- the cmdlet doesn't throw an exception. Remove the filer and use the -Identity parameter and the samaccountname from the CSV as you did in the second example.

You also don't mention if all of your user accounts are in the same domain. If you have a multi-domain forest you'll either have to use a distinguished name or search a Global Catalog and specify the root of the forest as the -SearchBase parameter value.

Since you don't mention what the problem is (except to say "none of them worked") it's not possible to tell you what to fix. But at the least, I'd start by verifying that the sAMAccountName values in the CSV don't have any trailing spaces.

I don't recall if the properties your populating in the $props hash with $null values will work if the Set-ADUser cmdlet's parameter specifies it accepts a string type. You may want to construct the $props hash by doing something like this "if ($user.city){$props.City = $user.City}" and simply omit the parameter if it isn't present in the CSV.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

VictorFlorncio-1904 avatar image
0 Votes"
VictorFlorncio-1904 answered

Thank you all for the answers.

Error from first script:

Get-ADUser : Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation
again.
At line:6 char:1
+ Get-ADUser -filter {name -eq $.name}|Set-ADUSer -MobilePhone $.Mobile ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], PSArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.Management.Automation.PSArgumentException,Microsoft.ActiveDirectory.Management.Commands.Get
ADUser


Get-ADUser : Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation
again.
At line:6 char:1
+ Get-ADUser -filter {name -eq $.name}|Set-ADUSer -MobilePhone $.Mobile ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], PSArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.Management.Automation.PSArgumentException,Microsoft.ActiveDirectory.Management.Commands.Get
ADUser




This is the error when I run the second script:

Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the
command again.
At line:17 char:12
+ set-aduser @props
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUser


Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the
command again.
At line:17 char:12
+ set-aduser @props
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUser

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered IanXue-MSFT edited

Hi,

In the first script it should be $_.name, not $.name . See if this works

 $USERS|Foreach{
 $name = $_.name
 Get-ADUser -filter {name -eq $name} |Set-ADUSer -MobilePhone $_.MobilePhone -StreetAddress $_.StreetAddress -City $_.City -Title $_.Title}

The second error indicates there's no cloumn of the name "samaccountname" in your csv file. In the image I can only see ”SamAccou“ in cloumn R. Check if there is a trailing space as Rich suggested above.

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hey Ian,

Thanks.

I Tried in your way and I got this output:

Get-ADUser : Variable: 'name' found in expression: $name is not defined.
At line:7 char:2
+ Get-ADUser -filter {name -eq $name} | Set-ADUSer -MobilePhone $_.Mob ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser


Get-ADUser : Variable: 'name' found in expression: $name is not defined.
At line:7 char:2
+ Get-ADUser -filter {name -eq $name} | Set-ADUSer -MobilePhone $_.Mob ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

0 Votes 0 ·

Have you added the line $name = $_.name ? Or you can try this

 $USERS|Foreach{
 Get-ADUser -filter "name -eq '$($_.name)'" |Set-ADUSer -MobilePhone $_.MobilePhone -StreetAddress $_.StreetAddress -City $_.City -Title $_.Title}


0 Votes 0 ·
VictorFlorncio-1904 avatar image
0 Votes"
VictorFlorncio-1904 answered RichMatheisen-8856 commented

Guys, I found other script and made some adjusts, but, I receive the error below:

Get-ADUser : Error parsing query: 'userPrincipalName eq 'vruiz'' Error Message: 'syntax error' at position: '19'.
At line:13 char:13
+ $user = Get-ADUser -Filter "userPrincipalName eq '$upn'"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Script



Get CSV content

$CSVrecords = Import-Csv "C:\Test.csv" -Delimiter ";"

Create arrays for skipped and failed users

$SkippedUsers = @()
$FailedUsers = @()

Loop trough CSV records

foreach ($CSVrecord in $CSVrecords) {
$upn = $CSVrecord.UserPrincipalName
$user = Get-ADUser -Filter "userPrincipalName eq '$upn'"
if ($user) {
try{
$user | Set-ADUser -Department $CSVrecord.Department -TelephoneNumber $CSVrecord.TelephoneNumber
} catch {
$FailedUsers += $upn
Write-Warning "$upn user found, but FAILED to update."
}
}
else {
Write-Warning "$upn not found, skipped"
$SkippedUsers += $upn
}

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Use "-eq" as the comparison operator. You're missing the hyphen in that script.

0 Votes 0 ·
RichMatheisen-8856 avatar image
1 Vote"
RichMatheisen-8856 answered dawsayan commented

Try this version of that script. It corrects the comparison operator in the -Filter parameter and adds the necessary "-ErrorAction STOP" to the Set-ADUser cmdlet. Without the ErrorAction the Set-ADUser won't throw a non-terminating exception and the Catch block will never be run.

 #Get CSV content
 $CSVrecords = Import-Csv "C:\Test.csv" -Delimiter ";"
    
 #Create arrays for skipped and failed users
 $SkippedUsers = @()
 $FailedUsers = @()
    
 #Loop trough CSV records
 foreach ($CSVrecord in $CSVrecords) {
         $upn = $CSVrecord.UserPrincipalName
         $user = Get-ADUser -Filter "userPrincipalName -eq '$upn'"
         if ($user) {
                 try {
                         $user | Set-ADUser -Department $CSVrecord.Department -TelephoneNumber $CSVrecord.TelephoneNumber -ErrorAction STOP
                 }
                 catch {
                         $FailedUsers += $upn
                         Write-Warning "$upn user found, but FAILED to update."
                 }
         }
         else {
                 Write-Warning "$upn not found, skipped"
                 $SkippedUsers += $upn
         }
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Key was "" double quotes around the Filter and -eq '' single quotes around the $upn
Thanks !

1 Vote 1 ·
VictorFlorncio-1904 avatar image
0 Votes"
VictorFlorncio-1904 answered RichMatheisen-8856 commented

Rich, after I posted that I already tried -eq.

I received this:

WARNING: USER1 not found, skipped
WARNING: USER2 not found, skipped

This is my CSV, if I open with notepad, its normal and delimited with ; and no spaces..

Damn :(

54111-image.png



image.png (16.8 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Try removing the single quotes surrounding the $upn variable in the filter.

0 Votes 0 ·

The data in the UserPrincipalName column looks suspicious to me. A UPN is usually (but not always) composed of the sAMAccountname name followed by "@" and a domain name.

If, in your Active Directory, the sAMAccountname and userPrincipalName are the same then you don't need to use a filter, you can use the -Identity parameter and the value in the UserPrincipalName column.


0 Votes 0 ·
VictorFlorncio-1904 avatar image
0 Votes"
VictorFlorncio-1904 answered RichMatheisen-8856 edited

Now I can find the users, but failed to Update.

I made some changes after Set-ADUser parameter and changed to JobTitle, but no success.

Import-Module ActiveDirectory


$CSVrecords = Import-Csv "C:\Test.csv" -Delimiter ";"


$SkippedUsers = @()
$FailedUsers = @()


foreach ($CSVrecord in $CSVrecords) {
$upn = $CSVrecord.UserPrincipalName
$user = Get-ADUser -Identity $upn
if ($user) {
try {
$user | Set-ADUser -JobTitle $CSVrecord.Jobtitle -ErrorAction STOP
}
catch {
$FailedUsers += $upn
Write-Warning "$upn user found, but FAILED to update."
}
}
else {
Write-Warning "$upn not found, skipped"
$SkippedUsers += $upn
}
}

WARNING: user1user found, but FAILED to update.
WARNING: user2 user found, but FAILED to update.
WARNING: user3 user found, but FAILED to update.
WARNING: user4 user found, but FAILED to update.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

There no "-JobTitle" parameter on the Set-ADUser. There is, however, a "-Title". That's probably what you want.

But you've made your Catch block too simple! You're hiding the reason for your being there! Try changing it a bit to help yourself figure out what's happened:

 catch {
     $Why = $_ | Out-String
     $FailedUsers += $upn
     Write-Warning "$upn user found, but FAILED to update.`n$Why"
 }


0 Votes 0 ·
RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered

Without meaning to be insulting, I think you'd benefit from reading this: Windows-PowerShell-4


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndrBorgeld-4035 avatar image
0 Votes"
AndrBorgeld-4035 answered AndrBorgeld-4035 edited

@RichMatheisen-8856 I saw this post, thank you for the reading tip! You can download the book certainly worth while!

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.