Can't get pipeline variable to evaluate


I would like to write the SamAccountName property of an account into the mailNickname property.

1 nice simple string…

Get-ADUser mdawson -Properties SamAccountName,Mail,MailNickName | Where-Object {($_.mail -ne $null) -and ($_.mailNickName -eq $null)} | Set-Aduser -Replace @{MailNickName = "$_.SamAccountName"}

I can’t for the life of me work out how to get the final Set-Aduser cmdlet to work, it fails to expand the $_.SamAccountName parameter and I end up with mailNickname being equal to “.SamAccountName”

Any ideas?



$_ is the current object in a pipeline. The current object concept exists when piping to a command that evaluates a script block. You are accessing $_.SamAccountName outside of a script block. A simple workaround for you is to pipe into Foreach-Object:

Get-ADUser mdawson -Properties SamAccountName,Mail,MailNickName |
    Where-Object {($_.mail -ne $null) -and ($_.mailNickName -eq $null)} | Foreach-Object { 
        Set-Aduser -Replace @{MailNickName = $_.SamAccountName}

You should also not use quotes around $.SamAccountName. This will cause $ to be expanded and then .SamAccountName will be added to the end of the expanded string. Quotes in this fashion can only be used with simple variable references. Your options are to not use quotes at all or use quotes around a sub-expression “$($_.SamAccountName)”.

Thank you very much. I knew it would be easy.