Mia Smith
Mia Smith

Reputation: 1

Change Active Directory titles for all csv users

I would like to change 150 employees their job title.

I have a csvfile called Titletest.csv with columns UserPrincipalName [the user.name under it] and Title [job title under it]

The PowerShell script:

Import-Module ActiveDirectory  

$users = Import-Csv -Path c:\scripts\Titlestest.csv | Foreach-Object {

$user = $_.user

$title = $_.title

#Selects the specified user and sets Job Title

Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Title $title

}

I get errors saying:

Get-ADUser : Variable: 'user' found in expression: $user is not defined.
At line:14 char:1
+ Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Titl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Can someone please advise?

Thank you.

Upvotes: 0

Views: 2299

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

The reason for your error is because $user has no assignment. You are attempting to assign $user the value of a property that does not exist. The header user apparently does not exist in your CSV file. See below for how to convert a csv into PowerShell objects and access their properties.

# Sample CSV TitleTest.csv
UserPrincipalName,Title
[email protected],Usurper
[email protected],CEO
[email protected],CFO

Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
    $user = $_.UserPrincipalName
    $title = $_.Title
    Get-ADUser -Filter 'UserPrincipalName -eq $user' | Set-ADUser -Title $title
}

Explanation:

When using Import-Csv on a proper CSV file, the first row of delimited data will be converted to the properties of all input objects. All succeeding rows will be converted to individual objects with the header properties and output as a collection (array) of those objects. If the -Header parameter is used, then values passed into the parameter will become the properties of the objects. It is important to have the same number of delimited items on each row to ensure proper mapping.

Once you are dealing with objects, you can access their property values using the member access operator .. The syntax is object.property. So since you have headers UserPrincipalName and Title, you will need to use $_.UserPrincipalName and $_.Title to access the associated values.

$_ is the current pipeline object within your Foreach-Object {} script block.

Note that you don't technically need to define $user and $title here. You can just access the properties directly from the current object:

Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
    Get-ADUser -Filter "UserPrincipalName -eq '$($_.UserPrincipalName)'" |
        Set-ADUser -Title $_.Title
}

Upvotes: 1

Related Questions