3

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?

5
  • There are some modules that would help you with that...for example: gallery.technet.microsoft.com/scriptcenter/… Mar 25, 2015 at 16:43
  • Have you tried replacing '.' with $env:computername ? Mar 25, 2015 at 18:14
  • 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
    Mar 25, 2015 at 19:42
  • Also tried to replace '.'with $env.computername but nothing changed. I always get just true as result.
    – Colorando
    Mar 25, 2015 at 19:44
  • If MinGW is installed (is included with Git), you can use C:\Program Files\Git\usr\bin\passwd.exe - it updates Windows password Jan 31, 2021 at 5:51

2 Answers 2

3

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!

0

I don't have enough points here to change it, but this question looks like a duplicate of this one.

2
  • No, in the linked question it's about changing password for user if in active directory. I don't use active directory.
    – Colorando
    Mar 25, 2015 at 19:25
  • "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. Mar 26, 2015 at 2:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .