Powershell to change email suffix of AD Contacts whose suffix is abc.com to xyz.com in a particular OU

Biju Thankappan 86 Reputation points
2021-05-19T02:13:19.887+00:00

I have the below code:
$LocalUsers = Get-ADObject -Filter {(objectClass -eq "contact") -and (mail -like '*gmail.com')} -SearchBase "OU=T,OU=Test,DC=contoso,DC=com" -Properties mail -ResultSetSize $null
$LocalUsers | foreach {$newUpn = $.email.Replace("gmail.com","contoso.com"); $ | Set-ADObject -mail $newUpn}

And get the below error:
Method invocation failed because [Microsoft.ActiveDirectory.Management.ADPropertyValueCollection] does not contain a method named 'Replace'.
At line:2 char:24

  • ... | foreach {$newUpn = $_.email.Replace("gmail.com","contoso.com"); ...
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • CategoryInfo : InvalidOperation: (:) [], RuntimeException
  • FullyQualifiedErrorId : MethodNotFound

Set-ADObject : A parameter cannot be found that matches parameter name 'mail'.
At line:2 char:99

  • ... Replace("gmail.com","contoso.com"); $_ | Set-ADObject -mail $newUpn ...
  • ~~~~~
  • CategoryInfo : InvalidArgument: (:) [Set-ADObject], ParameterBindingException
  • FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADObject

Thank you for your help!

Regards,
BT

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} vote

Accepted answer
  1. Anonymous
    2021-05-19T04:23:05.753+00:00

    Hi,

    For the first error, the property is "mail", not "email".
    For the second error, the Set-ADObject cmdlet has no "-mail" parameter. Please use "-replace" to set the mail attribute.

    $LocalUsers = Get-ADObject -Filter {(objectClass -eq "contact") -and (mail -like '*gmail.com')} -SearchBase "OU=T,OU=Test,DC=contoso,DC=com" -Properties mail -ResultSetSize $null  
    $LocalUsers | foreach {$newUpn = $_.mail.Replace("gmail.com","contoso.com"); $_ | Set-ADObject -Replace @{mail=$newUpn} }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.