# copyADUser.ps1
# Version 0.01

$fromUsername='mTyson'
$newUserFirstname='Bruce'
$newUserLastname='Lee'
$newPassword='SOMEPASSWORD'
$newEmailAddress='[email protected]'
$setProxyAddress=$false

function copyADUser{
  param(
    $fromUsername,
    $newUserFirstname,
    $newUserLastname,
    $newPassword,
    $newEmailAddress,
    $setProxyAddress=$false
  )
  try{
    Import-Module activedirectory
  }catch{
    write-warning $_
    return $false
  }
  $availableUserName=.{
    $index=0
    $x=($newUserFirstname.toLower())[$index]+$newUserLastname.tolower()
    do{
      $usernameExists=try{$null=get-aduser $x;$true}catch{$false}
      if($usernameExists){
        $index+=1
        $x=(($newUserFirstname.toLower())[0..$index] -join '')+$newUserLastname.tolower()
      }else{
        return $x
      }
    }until(!$usernameExists -or $newUserFirstname.length+$newUserLastname.length -eq $x.length)
    $number=1
    $x=($newUserFirstname.toLower())[$index]+$newUserLastname.tolower()
    do{
      $y=$x+"$number"
      $usernameExists=try{$null=get-aduser $y;$true}catch{$false}
      if($usernameExists){
        $number+=1
        $y=$x+"$number"
      }else{
        return $y
      }      
    }until($number -ge 10000)
    return $null
  }
  if(!$availableUserName){
    write-warning "Unable to proceed due to username being NOT available."
    return $false
  }
  function copyGroupMemberships($fromIdentity,$toIdentity){
    $ErrorActionPreference='stop'
    try{
      Import-module activedirectory
      $groupNames=(Get-ADPrincipalGroupMembership $fromIdentity).Name
      $groupNames|%{try{Add-ADGroupMember -Identity "$_" -Members $toIdentity -ea SilentlyContinue}catch{}}
      $currentMemberships=(Get-ADPrincipalGroupMembership $toIdentity).Name
      write-host "User '$env:USERDOMAIN\$toIdentity' now has these memberships:`r`n---------------------------------`r`n$($currentMemberships|out-string)"
      return $true
    }catch{
      write-warning $_
      return $false
    }
  }

  $fullName=$newUserFirstname+' '+$newUserLastname
  $newPrinciplename=$availableUserName+'@'+$env:USERDNSDOMAIN
  $securedPass=(ConvertTo-SecureString $newPassword -AsPlainText -Force)
  write-host "Creating UserID '$availableUserName' with full name of '$fullname', and setting the password of '$newPassword'"
  try{
    $copyAttributes=Get-ADUser -Identity $fromUsername -Properties StreetAddress,City,Title,PostalCode,Office,Department,Manager
    $targetOu=.{
$userObjectSplit=(get-aduser $fromUsername).DistinguishedName -split ','
if($userObjectSplit[0] -match '\\'){
return $x[2..$x.length] -join ','
}else{
return $x[1..$x.length] -join ','
}
    }
    New-ADUser -SAMAccountName $availableUserName -Name $fullName -GivenName $newUserFirstname -Surname $newUserLastname -Instance $copyAttributes -DisplayName $fullName -UserPrincipalName $newPrincipleName -AccountPassword $securedPass -ChangePasswordAtLogon $false -Enabled $true
    Set-ADUser -Identity $availableUserName -EmailAddress $newEmailAddress
    if($setProxyAddress){
      Set-ADUser -Identity $availableUserName -Add @{proxyAddresses="SMTP:$newEmailAddress";proxyAddressesForGapps="SMTP:$newEmailAddress"}
    }

    # This error would occur if UserPrincipleName is not specified or having conflicts
    # New-ADUser : The operation failed because UPN value provided for addition/modification is not unique forest-wide
    # At line:1 char:5
    # +     New-ADUser -Name $fullName -GivenName $newUserFirstname -Surname  ...
    # +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #     + CategoryInfo          : NotSpecified: (CN=Bruce Lee...DC=kimconnect,DC=com:String) [New-ADUser], ADException
    #     + FullyQualifiedErrorId : ActiveDirectoryServer:8648,Microsoft.ActiveDirectory.Management.Commands.NewADUser

    $currentIdentity=(Get-aduser $availableUserName).DistinguishedName
    Move-ADObject -Identity $currentIdentity -TargetPath $targetOu
    copyGroupMemberships $fromUsername $availableUserName
    return $true
  }catch{
    write-warning $_
    return $false
  }
}

copyADUser $fromUsername `
  $newUserFirstname `
  $newUserLastname `
  $newPassword `
  $newEmailAddress `
  $setProxyAddress