0

I'm beginner in powershell and I need your help. I need to compare the department attribute from the AD containing some text amd replacing by another value. But it doesn't work. Do I made a mistake below? Cheers

//Find the user and save the user in the variable 
$member = get-Aduser -f {GivenName -eq 'Jack'}

//check if the Departement field match with "Dep20 "
if($member.department -eq "Dep20")
{
    //Set "Dep21" in department field
    $member.Department = 'Dep21';
    set-AdUser -f {GivenName -eq $member.givenName} -departement $member.Department;
}
mklement0
  • 382,024
  • 64
  • 607
  • 775

1 Answers1

1

Some issues with your initial script

First Get-AdUser won't give you the property Department by default. You could have confirmed this by actually looking at the output of your Get-AdUser statement. You do need to add it to the list of properties explicitely.

get-Aduser -f {GivenName -eq 'Jack'} -Properties Department

Also, you did make a mistake in the Set-AdUser cmdlet. The parameter name you have written, at the time of my answer, is -departement. Instead, you need to set -department.

Finally, Get-AdUser could return multiple users (or none). Therefore, you need to account for that by checking how many $member were returned or to do a foreach to process none (if 0) or all of them the same. At least, that part is subjective to what you need but here would be my approach.

$member = get-Aduser -Filter 'GivenName -like "Jack*"' -Properties Department
$member | foreach {
    if ($member.Department -eq 'Dep20')
    {
        $_.Department = 'Dep21'
        set-AdUser $_  -Department $_.Department;
    }

}

Edit:

I modified my answer to switch the Filter parameter from a scriptblock (as your question) for a string filter as per mklement0 comment.

Because the Filter parameter is actually a string, giving it a script block will create problems on multiple occasions and you are better restrict yourself to the string type for this parameter.

See this for a more detailed explanation on the matter.

Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39