0

I have a .csv file that I am using to modify custom attributes on users in Active Directory, but PowerShell does not like the script:

Import-Csv -path c:\users\user\desktop\doc.csv | ForEach-Object  { 
            Set-ADUser $_.mail -replace @{
                ExtensionAttribute1 = $_.ExtensionAttribute1
            }
        }

I get the following error:

Set-ADUser : replace

At line:2 char:4

  • Set-ADUser $_.mail -replace @{

  • CategoryInfo: InvalidOperation: (user123:ADUser) [Set-ADUser], ADInvalidOperationException

  • FullyQualifiedErrorId: ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser

The CSV only has 2 columns:

extensionAttribute1,mail

Any help would be appreciated

5
  • 2
    Remove the space between @ and the opening bracket { Commented Jan 11, 2022 at 19:48
  • 2
    That's not even a valid syntax for Set-ADUser, nor is it valid to have the pipe (|) in a new line. also, you need have the opening brace for Foreach-Object in the same line unless you you use a continuation/escape mark: the back tick: `.There's no -Replace parameter, and if you're referring to the operator, it's still invalid syntax for that as well. What are your intentions? What is the expected result? Commented Jan 11, 2022 at 20:43
  • @Theo the way the code pasted added a space. the original code is @{ sorry for the confusion Commented Jan 11, 2022 at 21:11
  • I am trying to have the extensionAttribute1 be added to the users in AD based on their mail attribute Commented Jan 11, 2022 at 21:14
  • 1
    @Santiago, my fault! Had to confirm before I commented it lol but, now double checking, I see -Replace is a parameter. Thank you!:) Commented Jan 11, 2022 at 21:52

1 Answer 1

3

The -Identity parameter for Set-ADUser does not take an email address.
It needs either the DistinguishedName, objectGUID, SID or SamAccountName. You can also pipe a user object directly to the cmdlet.

Because of that, you need to first try to find the user with Get-ADUser and if that succeeds set the attribute.

Import-Csv -Path 'c:\users\user\desktop\doc.csv' | ForEach-Object { 
    $user = Get-ADUser -Filter "EmailAddress -eq '$($_.mail)'" -ErrorAction SilentlyContinue
    if ($user) {
        $user | Set-ADUser -Replace @{ extensionAttribute1 = $_.extensionAttribute1 }
    }
    else {
        Write-Warning "No user with email address '$($_.mail)' found.."
    }
}

PS. I always use the exact LDAP name inside the Hash for the key name when using -Add, -Replace etc. Case sensitive.

Sign up to request clarification or add additional context in comments.

1 Comment

@Theo This script adjust worked for me. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.