Windows: change own password of standard user by using commandline

5,470

I have found the answer:

$oldpw = "oldpassword"
$newpw = "newpassword"
$user = $env:username
$computer = $env:computername
$user = [adsi]"WinNT://$computer/$user"
$user.ChangePassword($oldpw, $newpw)

This worked for me. Thank you for your replies!

Share:
5,470

Related videos on Youtube

Colorando
Author by

Colorando

Updated on September 18, 2022

Comments

  • Colorando
    Colorando over 1 year

    I want to change the password of the current logged in Windows user (no Active Directory) in a scriptable way. The users have the right to change their own passwords and already can change the password via GUI. But I've no way to integrate this in a script.

    I've tried net use %user% %newpassword% but that only seems to work if the current user has admin rights.

    I've also tried a powershell script:

    param (
        [string]$oldPassword = $( Read-Host "Old Password"),
        [string]$newPassword = $( Read-Host "New Password")
    )
    
    $MethodDefinition = @'
    [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
    public static extern bool NetUserChangePassword(string domainname, string username, string oldPassword, string newPassword);
    '@
    
    $NetAPI32 = Add-Type -MemberDefinition $MethodDefinition -Name 'NetAPI32' -Namespace 'Win32' -PassThru
    
    $NetAPI32::NetUserChangePassword('.', $env:username, $oldPassword, $newPassword)
    

    This gives "True" but nothing changes.

    Has anyone an idea how I can change the password via script?

    • Tim Ferrill
      Tim Ferrill about 9 years
      There are some modules that would help you with that...for example: gallery.technet.microsoft.com/scriptcenter/…
    • Mathias R. Jessen
      Mathias R. Jessen about 9 years
      Have you tried replacing '.' with $env:computername ?
    • Colorando
      Colorando about 9 years
      Thank you for the link to the script center. I've tried following: $user = $env:username $password = "xxxxxxxxxx" $computer = $env:computername $user = [adsi]"WinNT://$computer/$user,user" $user.SetPassword($Password) $user.SetInfo() but I always get access denied.
    • Colorando
      Colorando about 9 years
      Also tried to replace '.'with $env.computername but nothing changed. I always get just true as result.
    • Mykola Bogdiuk
      Mykola Bogdiuk over 3 years
      If MinGW is installed (is included with Git), you can use C:\Program Files\Git\usr\bin\passwd.exe - it updates Windows password
  • GuitarPicker
    GuitarPicker about 9 years
    "On Windows Server 2008 R2, I have a standard (non-administrator) local user (not an Active Directory account, though the server is in a domain) " It's about a local account for an Active Directory member server (non DC). Those are treated the same as local accounts on standalone machines. If the answer in the other thread works, then it should apply here as well.