title: Powershell and Exchange: Detecting When Values Don't Need To Change
body: <p>I'm building a tool for handling user renaming in AD and Exchange using Powershell.</p>
  <p>There's a section of the script that I've used in to build appropriate UPN/PrimarySMTPAddress values based on provided information that checks for conflicts with values in other AD User Objects and returns an available and appropriate value for the script to use.</p>
  <p>To account for cases where the UPN/PrimarySMTPAddress generated from the new values collected earlier in the script may result in the new proposed UPN being the same as the current value, the script's current method of simply finding the next available appropriate UPN isn't good enough.</p>
  <p>To try to deal with this, I added a simple If checking to see if the generated UPN value was the same as the current AD User Object's UPN, but this is failing and I'm not sure why.</p>
  <p>Here is my current code complete with the attempt to catch the duplicate:</p>
  <p><code>$UPNGivenName</code> is the First Name, alpha characters and dashes only. <br />
  <code>$UPNSurname</code> is the provided Last Name, alpha characters and dashes only.<br />
  <code>$SMTPDomain</code> is the the domain email suffix: eg <em>@contoso.com</em><br />
  <code>$UserAdUpn</code> is pulled from the target AD object's UniversalPrincipalName. Earlier in the script I've already confirm a valid AD Object is found and pulled its UniversalPrincipalName value directly into $UserAdUpn.</p>
  <pre><code>If ($ChangeUPN -eq 'Y') {
      $ProposedUPNBase = $UPNGivenName + &quot;.&quot; + $UPNSurname
      $checkNewUPNDupe = &quot;$ProposedUPNBase$SMTPDomain&quot;
  
      If ($UserAdUpn -eq $checkNewUPNDupe) {
          # Generated UPN matches current UPN
          Write-Host &quot;New UPN matches current UPN. No change.&quot;
          $ChangeUPN = 'N'
      }
      Else {
  </code></pre>
  <blockquote>
  <p>#... Loop for crazy UPN checking/creation stuff. Not relevant</p>
  </blockquote>
  <pre><code>    }
  }
  </code></pre>
  <p>EDITS: (Stuff I should have thought to include to begin with, really)</p>
  <p>The Error: Even though I know the current UPN and the proposed UPN are the same, the duplicate check doesn't trigger and a new UPN is created.</p>
  <p>Added info on the source of UserAdUpn above.</p>