Powershell – Windows: change own password of standard user by using commandline

passwordpowershellscriptinguserswindows-command-prompt

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?

Best Answer

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!