Search code examples
powershellactive-directoryattributes

Powershell: how to set 'preferredLanguage' in on-premise Active Directory for every User based on his AD-Group membership?


My goal is to change the "preferredLanguage" attribute in Active Directory for all Users in one AD-Group.

I am executing the following code in two separate lines:

$Users_UK = Get-AdGroupMember -identity "AD-Group-UK"
Get-ADUser $Users_UK -Properties preferredLanguage | Set-ADUser -Replace @{preferredLanguage = "en"}

However, the second line generates an error and I can't find the exact cause:

Get-ADUser : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser' required by parameter 'Identity'. Specified method is not supported.
At line:1 char:12
+ Get-ADUser $Users_UK -Properties preferredLanguage | Set-ADUser -Rep ...
+            ~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Solution

  • The error is because you're binding multiple group member objects to the -Identity parameter from Get-ADUser when that parameter only takes a single user. Piping should solve your issue:

    $Users_UK = Get-AdGroupMember -identity "AD-Group-UK"
    $Users_UK | Get-ADUser -Properties preferredLanguage |
        Set-ADUser -Replace @{ preferredLanguage = "en" }
    

    However, what I recommend you if you will constantly update the members of that group is to query only users that are a member of that group and their preferredLanguage is not en, this way you can avoid extra overhead:

    $groupDn = (Get-ADGroup 'AD-Group-UK').DistinguishedName
    $users = Get-ADUser -LDAPFilter "(&(memberOf=$groupDN)(!preferredLanguage=en))"
    if ($users) {
        $users | Set-ADUser -Replace @{ preferredLanguage = 'en' }
    }