Powershell script : Set-ADUser -clear with multiple attributes in variable
I want to clear multiple attributes by using variable in Powershell script (version 5.1.17763.1007)
It's work :
Set-ADUser -Identity $($user.SID) -Clear Initials,info
It's work also:
$emptyParams='Initials'
Set-ADUser -Identity $($user.SID) -Clear $emptyParams
It's not work :
$emptyParams='Initials,info'
Set-ADUser -Identity $($user.SID) -Clear $emptyParams
and display :
Set-ADUser : The specified directory service attribute or value does not exist Parameter name: Initials,info At Set-ADUserDesc.ps1:32 char:9 + Set-ADUser -Identity $($user.SID) -Clear $emptyParams + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (S-1-5-21-414636...1575523350-2106:ADUser) [Set-ADUser], ArgumentException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser
Can you explain-me why ?
Best regards,
Solution 1:
To directly answer your question of why the third method does not work:
There is no attribute by the name Initials,Info
which is why the cmdlet fails. Your input (a string with a comma) is not the same as an array of strings.
The docmentation for the cmdlet Set-AdUser indicates that the -Clear attributes accepts an array of strings (or a single string, which would just be an array with a single element) as valid input:
Set-ADUser
...
[-Clear <String[]>]
...
Let's go over each scenario you covered in your question.
Set-ADUser -Identity $($user.SID) -Clear Initials,info
The first method supplies two strings separated by a comma (this is interpreted as an array of strings) to the -Clear parameter. Good.
$emptyParams='Initials'
Set-ADUser -Identity $($user.SID) -Clear $emptyParams
The second method is supplying a single string (or an array of a single element) to the -Clear parameter. Good.
$emptyParams='Initials,info'
Set-ADUser -Identity $($user.SID) -Clear $emptyParams
The final method is actually supplying the attribute "Initials,Info". As noted above, this is a single string with commas in it, and the cmdlet iterprets it as a single argument.
To achieve what I think you're going for, you'll need to build and supply an array of valid attribute names. This should work:
$emptyParams = @()
$emptyParams += "Initials"
$emptyParams += "Info"
Set-ADUser -Identity $($user.SID) -Clear $emptyParams
And actually, this should work, too:
$emptyParams='Initials,info'
Set-ADUser -Identity $($user.SID) -Clear $emptyParams.Split(',')
Solution 2:
You can symply do it by creating a PowerShell array:
$emptyParams=@('Initials','info')
Set-ADUser -Identity $($user.SID) -Clear $emptyParams
or 1 line format
Set-ADUser -Identity $($user.SID) -Clear @('Initials','info')