Shell – PowerShell – IF statement case insensitive

active-directoryexchangepowershell

I am trying to write a PowerShell script that will cycle through the ProxyAddresses for all of my AD user objects. If a user has a SMTP address with USER@DOMAIN.LOCAL, I want it to check if they also have a matching SMTP address of USER@DOMAIN.COM and if not then add it, etc.

$ADobjects = @(Get-ADObject -Filter 'objectClass -eq "User"' -Properties mailNickname,ProxyAddresses -SearchBase "OU=Test,DC=domain,DC=local")

$TempArr = @()
$OldDomain = "@domain.local"
$NewDomain = "@domain.com"

$ADobjects | ForEach-Object { ## Cycle thru each AD object
    $PrimaryProxyAddress = $_.mailNickname+$NewDomain
    $TempStr = ""
    $TempAdd = ""
    If ($ADobjects.Count -ge 1) ## Make sure there is at least one item to work on
        {
        $TempArr = $_.ProxyAddresses ## Set $TempArr so that it contains all of the proxy addresses
        $TempArr | ForEach-Object { ## Cycle thru each proxy address of each AD object
        If ($_.Contains($OldDomain) -eq "True") ## Does the proxy address contain the old domain?
            { ## Come here if the proxy address contains the old domain
            $TempStr = $_ -replace $OldDomain, $NewDomain ## Replace the $OldDomain name with $NewDomain
            If ($TempArr.Contains($TempStr) -ne "True") ## See if we already have an address with the new domain name
                {
                write-host $TempStr
                $TempAdd = $TempAdd + " " + $TempStr ## We don't have one so add it to the list of SMTP addresses to add
                ## I've removed all of the addition stuff to keep the script shorter
                }
            }
        }
        }
}

It works until I get to the part

If ($TempArr.Contains($TempStr) -ne "True")

The $TempArr array may be something like

“SMTP:user@domain.local smtp:user@domain.com smtp:noone@domain.local smtp:user@newold.com x400 etc”

The $TempStr may be something like

“SMTP:user@domain.com”

My $TempStr does exist in the $TempArr array but my IF statement never returns TRUE (so it always thinks that the IF statement is –ne TRUE).

Isn’t CONTAINS supposed to be case insensitive by default in PowerShell? If it is case insensitive, doesn’t “SMTP:user@domain.com” -eq “smtp:user@domain.com”? Or is it maybe a data-type issue (I don’t get any errors) since one is an array and the other is a string? What am I missing here?

Thanks much

Best Answer

Isn’t CONTAINS supposed to be case insensitive by default in PowerShell?

The -contains operator is case insensitive.

The .Contains() method is case sensitive.

If you want to use the Contains() method, convert both strings to one case before compare. Something like:

If ($TempArr.ToLower().Contains($TempStr.ToLower()) -ne "True")
Related Question