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?

Colorando
  • 61
  • 1
  • 5
  • There are some modules that would help you with that...for example: https://gallery.technet.microsoft.com/scriptcenter/f75801e7-169a-4737-952c-1341abea5823 – Tim Ferrill Mar 25 '15 at 16:43
  • Have you tried replacing `'.'` with `$env:computername` ? – Mathias R. Jessen Mar 25 '15 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 '15 at 19:42
  • Also tried to replace `'.'`with `$env.computername` but nothing changed. I always get just true as result. – Colorando Mar 25 '15 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 – Mykola Bohdiuk Jan 31 '21 at 05:51

2 Answers2

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!

Colorando
  • 61
  • 1
  • 5
0

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

GuitarPicker
  • 404
  • 2
  • 8
  • 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 '15 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. – GuitarPicker Mar 26 '15 at 02:54