Skip to content

Instantly share code, notes, and snippets.

@jetersen
Last active November 4, 2019 08:27
Show Gist options
  • Save jetersen/0503d77aa6e03142865dcd19f8f93abf to your computer and use it in GitHub Desktop.
Save jetersen/0503d77aa6e03142865dcd19f8f93abf to your computer and use it in GitHub Desktop.
Change user password with freedom on Windows

Windows for some reason does not allow user to copy/paste password when using their interface to change password.

However when you rely on password managers it can be somewhat frustrating to input longer password, so you tend to cheap out.

This script tries to fix Windows shortcomings and actually provide users with the freedom to change password in a secure way.

Usage:

Here the script will default to logged in user

.\change-password.ps1
About to change password for DOMAIN\joseph petersen
Provide old password: *********
Provide new password: ******************************
Successfully changed password

You can also provide another username

.\change-password.ps1 a-jpt
About to change password for DOMAIN\a-jpt
Provide old password: ************
Provide new password: ******************************
Successfully changed password
param (
[string] $USERNAME = $env:USERNAME
)
function getPasswordFromUser {
param(
[string] $desc
)
$input = Read-Host "$desc" -AsSecureString
$output = New-Object System.Management.Automation.PSCredential($USERNAME, $input)
Write-Output $output
}
function getPassword {
param (
[PSCredential] $Credential
)
Write-Output $Credential.GetNetworkCredential().Password
}
function Write-ColorOutput($ForegroundColor) {
[Console]::ForegroundColor = $ForegroundColor
if ($args) {
Write-Output $args
}
else {
$input | Write-Output
}
[Console]::ResetColor()
}
Write-Output "About to change password for $env:USERDOMAIN\$USERNAME"
$old = getPasswordFromUser "Provide Old Password"
$new = getPasswordFromUser "Provide New Password"
$user = [adsi]("WinNT://$env:USERDOMAIN/$USERNAME, user")
try {
$user.ChangePassword($(getPassword $old), $(getPassword $new))
"Successfully changed password" | Write-ColorOutput green
}
catch {
"Failed to change password" | Write-ColorOutput red
$_.Exception.Message -replace "`n|`r" | Write-ColorOutput red
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment