# User input variables
$adminUsername='intranet\kim-a'
$adminPassword='SOMECOMPLEXPASSWORD'
$userId='kim'
$newPassword='SOMECOMPLEXPASSWORD'
$domainController='intranet.kimconnect.com'

# Auto-gen Variables
$encryptedPassword=ConvertTo-SecureString $adminPassword -AsPlainText -Force
$adminCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminUsername,$encryptedPassword

function resetUserPassword{
  param(
    $userId,
    $newPassword,
    $changeAtNextLogon,
    $adminCredentials,
    $domainController=$env:USERDNSDOMAIN
  )
  $psSession=if($adminCredentials){
    new-pssession -computername $domainController -credential $credentials
  }else{
    new-pssession -computername $domainController
  }  
  $scriptBlock={
    param($userId,$newPassword,$changeAtNextLogon)
      try{
        $newSecuredPassword=(ConvertTo-SecureString -AsPlainText $newPassword -Force)
        Set-ADAccountPassword -Identity $userId -Reset -NewPassword $newSecuredPassword -PassThru -Confirm:$false
        Unlock-ADAccount -Identity $userId
        if($changeAtNextLogon){
          Set-ADUser -ChangePasswordAtLogon $true -Identity $userId -Confirm:$false -verbose
        }
        write-host "$userId's password has been reset to $newPassword successfully!"
        return $true
      }catch{
        write-warning $_ 
        return $false
      }  
  }
  if($psSession.State -eq 'Opened'){
    $result=invoke-command -session $psSession -scriptblock $scriptblock -args $userId,$newPassword,$changeAtNextLogon
    remove-pssession $psSession
    return $result
  }else{
    write-warning "$env:computername is unable to init WinRM into $domainController"
    return $false
  }  
}

resetUserPassword `
  -userId $userId `
  -newPassword $newPassword `
  -changeAtNextLogon $false `
  -adminCredentials $adminCredentials `
  -domainController $domainController
# Sample Output - failure
PS C:\Windows\system32> resetUserPassword $userId $newPassword $false $adminCredentials $domainController
WARNING: The password does not meet the length, complexity, or history requirement of the domain.
False

# Sample Output - success
PS C:\Windows\system32> resetUserPassword $userId $newPassword $false $adminCredentials $domainController
kim password has been reset to $newPassword successfully!
True