Powershell Rewrite SAMAccountName and UPN

The below script will rewrite the samaccountname and upn of users within your search scope to the format of firstinitial+lastname. If a conflict is detected a number is appended and retried until the set-aduser command succeeds. The script makes no attempt on accounts missing either firstname or lastname.

$searchbase = "OU=OrgUnit,DC=DOMAIN,DC=COM"
$srcusers = Get-ADUser -filter * -SearchBase $searchbase

foreach($s in $srcusers){
If ($s.Surname -like "*" -and $s.GivenName -like "*"){
$newname = (($s.GivenName).Substring(0,1)+$s.Surname)
$n = 1
$errvar = $null
set-aduser -Identity $s.samaccountname `
-SamAccountName $newname -UserPrincipalName ($newname + "@phsi.us") `
-ErrorAction Continue -ErrorVariable errvar -Verbose
$number = $n++
$newname = ((($s.GivenName).Substring(0,1)+$s.Surname) + $number)
$newname = $newname.Replace(".","")
$newname = $newname.Replace(" ","")

until ($errvar.count -eq 0)