0
votes

Sorry if this is quite simple, but I am new to powershell.

I am currently using the following script to add proxyAddress values to users in Active Directory:

Get-ADUser -Filter * -SearchBase 'OU=myou,DC=mydc' -Properties proxyaddresses |

Foreach {Set-ADUser -identity $_ -Add `

@{'ProxyAddresses'=@(("{0}{1}@{2}"-f 'smtp:', $_.name, 'mydomain.com'),("{0}{1}.  {2}@{3}" -f 'SMTP:', $_.givenName, $_.Surname, 'mydomain.com'))} }

However, for the next few OU's the givenName and surname values are blank, the name is stored in displayName in the following format "Firstname Surname".

How can I modify the script so instead of taking givenName period Surname, it will take displayName and replace the whitespace with a period?

E.G. A user with displayName "Joe Bloggs" would be given the value SMTP:[email protected]

2

2 Answers

0
votes

Try something like this. A simple replace operation on the value of displayname, and a few adjustments.

#Include displayname property
Get-ADUser -Filter * -SearchBase 'OU=myou,DC=mydc' -Properties displayname, proxyaddresses |

Foreach {
    #Used ($_.displayname.trim() -replace ' ', '.') and modified string format.
    Set-ADUser -identity $_ -Add @{
        'ProxyAddresses'=@(("{0}{1}@{2}"-f 'smtp:', $_.name, 'mydomain.com'),("{0}{1}.  {2}@{3}" -f 'SMTP:', ($_.displayName.trim() -replace ' ', '.'), 'mydomain.com'))
    }
}
0
votes

Not tested, but something like this maybe:

Get-ADUser -Filter * -SearchBase 'OU=myou,DC=mydc' -Properties proxyaddresses,displayname |

  Foreach {
            $ProxyAddresses = @("{0}{1}@{2}"-f 'smtp:', $_.name, 'mydomain.com')

            if ($_.surname)
              { $ProxyAddresses += "{0}{1}.  {2}@{3}" -f 'SMTP:', $_.givenName, $_.Surname, 'mydomain.com'}

             else 
              { 
                $UserPart = $_.DisplayName.trim().replace(' ','.')
                $ProxyAddresses += "{0}{1}@{2}"-f 'smtp:', $UserPart, 'mydomain.com'
              }
            }

Set-ADUser -identity $_ -Add @{'ProxyAddresses'= $ProxyAddresses }