trying to replace mailNickname for all user with their own samaccountname:
Import-Module activedirectory
$SAM = (Get-ADUser -SearchBase "OU=Staged,OU=corp,DC=mycompany,DC=com" -Filter * | select samaccountname)
foreach ($User in $SAM.samaccountname)
{
Set-ADUser $User -Replace @{mailNickName = "$SAM"}
}
This script sets mailNickName blank. Any idea? Thank you
Best Answer
To fix your problem with the least code change necessary, you should change your
$SAM
reference to$User
in theSet-ADUser
call. You're currently setting mailNickName to the user object returned byGet-ADUser
and not the sAMAccountName you're iterating over.Your variable names are a bit confusing though because they're named somewhat opposite of what the names actually represent. In your code
$SAM
is actually a list of ADUser objects that have all of their properties filtered out except for samaccountname. Your$User
variable in the foreach loop is actually the samaccountname string from each user object.Here's a minor variation of your code with changed variable names and the extraneous select statement removed.
Here's another variation that uses
ForEach-Object
's%
alias directly against the results of theGet-ADUser
call.