I am writing a script that will update user attributes in Active Directory from a CSV file. I am down to only one error now and it is to do with the syntax. Not sure what the correct syntax is; I have provided the error that I receive when I run the script.
Here is the script to update AD users from CSV file.
#Updates AD user attributes from CSV file
$credential = Get-Credential
#Load data from file.csv
$ADUsers = Import-csv file_location
# Server
$server = "127.0.0.1"
# Count variable for number of users update
$count = 0
#Go through each row that has user data in the CSV we just imported
foreach ($User in $ADUsers)
{
# Read user data from each field in each row and assign to variables.
$Username = $User.Username
$Title = $User.Title
$Office = $User.Office
$Description = $User.Description
#Check to see if the user already exists in AD. If they do, we update.
if (Get-ADUser -Filter "SamAccountName -eq $Username" -Server $server -Credential $credential)
{
#Set User attributes
Set-ADUser -Title $Title -WhatIf `
-Office $Office -WhatIf `
-Description $Description -WhatIf
# Print that the user was updated
Write-Host $Username "- User attributes have been updated." -ForegroundColor Yellow
# Update Count
$count += 1
}
}
# Print the number of updated users
Write-Host $count "Users have been updated" -ForegroundColor Green
Here is the error I am getting when I run the script
Get-ADUser : Error parsing query: 'SamAccountName -eq ADUSER' Error Message: 'syntax error' at position: '20'.
At file_location from CSV.ps1:35 char:6
+ if (Get-ADUser -Filter "SamAccountName -eq $Username" -Server $se ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUse
r
0 Users have been updated