Peter Hinchley

Learning in Public

✪ Changing Your Expired Active Directory Password via PowerShell

Ever tried to log onto a server, only to hit a brick wall, because NLA is enabled, and your password has expired? Unless you are able to connect via an interactive console session, which may not be possible, you might think you are out of luck. However, if you have access to a domain controller in the domain over SMB (only TCP port 445 is required), you can try changing your expired password with the following PowerShell code (where $dc identifies the name of the domain controller):

$username = 'phinchley'
$dc = 'dc.lab.hinchley.net'

$old = 'Passw0rd1#'
$new = 'Something!'

$code = @'
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
public static extern bool NetUserChangePassword(string domain, string username, string oldpassword, string newpassword);
'@

$NetApi32 = Add-Type -MemberDefinition $code -Name 'NetApi32' -Namespace 'Win32' -PassThru

if ($result = $NetApi32::NetUserChangePassword($dc, $username, $old, $new)) {
  write-host 'Password change failed.'
} else {
  write-host 'Password change successful.'
}

This code relies on the NetUserChangePassword function, and it should succeed where other approaches will fail, as it doesn't attempt an LDAP bind prior to changing the expired password.