Since it's not necessary to pick one particular domain1.com address, try this.
I've added a flag variable to set the primary address only once per user.
Furthermore I switched to the -like operator, as the -match operator isn't necessary and just produces more overhead if not used correctly.
And I've added the "start of string" regex character to your replacement parts (-replace also uses regex pattern)
Get-ADUser -Filter * -SearchBase 'OU=users_test,OU=Test,DC=test,DC=local' -Properties name, mail, ProxyAddresses |
ForEach-Object {
# flag to avoid further processing after first match
$userDone = $false
$proxies = $_.ProxyAddresses |
ForEach-Object {
$proxyAddress = $_ -replace '^SMTP', 'smtp'
if (!$userDone -and $proxyAddress -like '*@domain1.com') {
$proxyAddress -replace '^smtp', 'SMTP'
$userDone = $true
} else {
$proxyAddress
}
}
$_.ProxyAddresses = $proxies
#Set-ADUser -instance $_
Write-Host $proxies
}
Update 2021-01-13
Here's an update according to your request in the comments below.
Could you show me how I could use the same script that would choose first.last@domain1.com. The ForEach should change to primary the one that has first.last.
Now regex makes more sense ;)
The code is untested against Active Directory, but should work.
The regex pattern in short:
(?i) >case-insensitive match (=regex option)
^ >start of string
(?: >non-capturing group (capturing is not required in your case)
smtp: >starts with 'smtp:'
[^.@]+ >matches any char at least once excluding '.' and '@'
. >matches '.' once
[^.@]+ >matches any char at least once excluding '.' and '@'
@domain1.com >matches '@domain1.com'
)
$ >end of string
For more details please look at: https://regex101.com/r/atKdSw/1/
I've additionally added a warning when no match has been made due to whatever reason. The addresses are then not returned back to the source property (the addresses remain original).
# pattern matches only addresses with format "*.*@domain.com" --> <anythingButDotOr(at)>.<anythingButDotOr(at)>@domain.com
$newPrimaryAddressMatchPattern = '(?i)^(?:smtp:[^.@]+.[^.@]+@domain1.com)$'
Get-ADUser -Filter * -SearchBase 'OU=users_test,OU=Test,DC=test,DC=local' -Properties name, mail, ProxyAddresses |
ForEach-Object {
# flag to avoid further processing after first match
$userDone = $false
$proxies = $_.ProxyAddresses |
ForEach-Object {
$proxyAddress = $_ -replace '^SMTP', 'smtp'
if (!$userDone -and $proxyAddress -match $newPrimaryAddressMatchPattern) {
$proxyAddress -replace '^smtp', 'SMTP'
$userDone = $true
} else {
$proxyAddress
}
}
if (!$userDone) {
# if no address matched the pattern required for setting the new primary one
Write-Warning "Unable to set new primary address for $($_.UserPrincipalName) | $($_.CanonicalName)!"
} else {
$_.ProxyAddresses = $proxies
}
#Set-ADUser -instance $_
Write-Host $proxies
}