Youssef Karami
Youssef Karami

Reputation: 75

Using PowerShell to update AD users from CSV file

I'm using a PowerShell script to add some information to all users in AD. For some reason, I keep getting an error message if the user has a apostrophe in their name (e.g Tim O'Reilly).

How can I format the script so it will include names with apostrophe ?

My script:

# Import AD Module
Import-Module ActiveDirectory

write-Host 'Starting to update AD Attributes.......' -NoNewline -ForegroundColor Yellow
# Import CSV into variable $users

$users = Import-Csv -Path C:\Scripts\users.csv

# Loop through CSV and update users if the exist in CVS file

foreach ($user in $users) {
#Search in specified OU and Update existing attributes
Get-ADUser -Filter "displayName -eq '$($user.Name)'" -Properties * -SearchBase "DC=My,DC=domain,DC=com" |
Set-ADUser -Company $($user.Email)
}

Write-Host 'done!' -ForegroundColor Green

And this is the error message I'm getting:

Get-ADUser : Error parsing query: 'displayName -eq 'Tim O'Reilly'' Error Message: 'syntax error' at position: '29'. At C:\Scripts\Update-information\Update-Users-2.ps1:13 char:1 + Get-ADUser -Filter "displayName -eq '$($user.Name)'" -Properties * -S ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr osoft.ActiveDirectory.Management.Commands.GetADUser

I'd really appreciate any help I can get here.

Thank you,

Upvotes: 0

Views: 968

Answers (1)

Andrii Matus
Andrii Matus

Reputation: 186

You can use some custom delimiter in your csv file instead of modifying your script. Just divide your data with custom char like ":" (Tim : O'Reilly), and add delimiter switch for import-csv cmdlet, like

$users = Import-Csv -Path C:\Scripts\users.csv -Delimiter :

Upvotes: 1

Related Questions