Skip to content

Instantly share code, notes, and snippets.

@lowleveldesign
Last active February 12, 2023 13:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lowleveldesign/7af4a0c91fab4b3bc0dd9c752ed4f1ce to your computer and use it in GitHub Desktop.
Save lowleveldesign/7af4a0c91fab4b3bc0dd9c752ed4f1ce to your computer and use it in GitHub Desktop.
Change domain password in PowerShell
$DllImport = '[DllImport("netapi32.dll", CharSet = CharSet.Unicode)] public static extern int NetUserChangePassword(string d, string u, string oldpass, string newpass);'
$NetApi32 = Add-Type -MemberDefinition $DllImport -Name 'NetApi32' -Namespace 'Win32' -PassThru
Write-Host -NoNewLine "Full domain name (for example, example.com): "
$Domain = Read-Host
$Context = [System.DirectoryServices.ActiveDirectory.DirectoryContext]::new([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain, $Domain)
$DomainController = ([System.DirectoryServices.ActiveDirectory.DomainController]::FindOne($Context)).Name
Write-Host -NoNewLine "Old password: "
$OldPass = Read-Host
Write-Host -NoNewLine "New password: "
$NewPass = Read-Host
$NetApi32::NetUserChangePassword($DomainController, $env:USERNAME, $OldPass, $NewPass)
# Error resulats are described in this doc: https://docs.microsoft.com/en-us/windows/win32/api/lmaccess/nf-lmaccess-netuserchangepassword
# ERROR_ACCESS_DENIED -> 5
# ERROR_INVALID_PASSWORD -> 86
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment