Windows – Powershell | Replace mailNickname with variable

active-directorypowershellwindows

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 the Set-ADUser call. You're currently setting mailNickName to the user object returned by Get-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.

$users = Get-ADUser -SearchBase "OU=Staged,OU=cor,DC=mycompany,DC=com" -Filter *
foreach ($user in $users) {
    Set-ADUser $user -Replace @{ mailNickName = "$($user.samaccountname)" }
}

Here's another variation that uses ForEach-Object's % alias directly against the results of the Get-ADUser call.

Get-ADUser -SearchBase "OU=Staged,OU=cor,DC=mycompany,DC=com" -Filter * | %{
    Set-ADUser $_.DistinguishedName -Replace @{ mailNickName = $_.samaccountname }
}