$MethodDefinition = @' [DllImport("netapi32.dll", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall,SetLastError=true )] public static extern uint NetUserChangePassword ( [MarshalAs(UnmanagedType.LPWStr)] string domainname, [MarshalAs(UnmanagedType.LPWStr)] string username, [MarshalAs(UnmanagedType.LPWStr)] string oldpassword, [MarshalAs(UnmanagedType.LPWStr)] string newpassword ); '@ $NetAPI32 = Add-Type -MemberDefinition $MethodDefinition -Name 'NetAPI32' -Namespace 'Win32' -PassThru function convert_sec_str { param([System.Security.SecureString]$str) $result = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($str)) $result } function verify_new_pw { param( [System.Security.SecureString]$new, [System.Security.SecureString]$confirm ) $new_conv = convert_sec_str $new $confirm_conv = convert_sec_str $confirm if ( $new_conv -eq $confirm_conv ) { 0 } else { 1 } } function changepw { $domain = $( Read-Host "Domain") $username = $( Read-Host "Username") $oldP = $( Read-Host "Old password" -AsSecureString) $newP = $( Read-Host "New password" -AsSecureString) $confirm_P = $( Read-Host "Confirm New Password" -AsSecureString) if ( $( verify_new_pw $newP $confirm_P ) -eq 0 ) { $oldPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($oldP)) $newPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($newP)) $result = $NetAPI32::NetUserChangePassword($domain, $username, $oldPassword, $newPassword) echo "Result (should be 0): ${result}" Read-Host "Press Enter to exit" # exit 0 } else { Write-Output "New password did not match confirmed password, exiting" Read-Host "Press enter to exit" # exit 1 } } changepw