Skip to content

Instantly share code, notes, and snippets.

@bryanvine
Last active October 12, 2015 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanvine/3536a1e9760b2479b00e to your computer and use it in GitHub Desktop.
Save bryanvine/3536a1e9760b2479b00e to your computer and use it in GitHub Desktop.
#Requires -Version 2
Function Set-UserPassword{
<#
.SYNOPSIS
Remotely sets local user password
.DESCRIPTION
Uses the [ADSI] object type to remotely connect to SAM to set user object password.
.PARAMETER ComputerName
Specifies one or more server names.
.PARAMETER Username
Specifies the local user account which you wish set the password.
.PARAMETER Password
Specifies the password which you wish to set. If not specified, you will be prompted.
.EXAMPLE
Get-Content .\myserverlist.txt | Set-UserPassword -Username 'Admin' -Password 'pass123'
This will set the password for user Admin on all computers listed in the myserverslist.txt
.LINK
http://www.bryanvine.com/2015/10/powershell-script-set-userpassword.html
.NOTES
Author: Bryan Vine
Last updated: 10/12/2015
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,valuefrompipeline=$true,Position=0)]
[alias("CN","MachineName","ServerName","Server")][ValidateNotNullOrEmpty()][string[]]
$ComputerName,
[Parameter(Mandatory=$true,Position=1)][string]
$Username,
[Parameter(Mandatory=$false,Position=2)][string]
$Password
)
BEGIN{
$allServers = @()
if(!$Password){
$Password = (Get-Credential -UserName $Username -Message "Enter net password to set").GetNetworkCredential().Password
}
}
PROCESS{
$allServers += $ComputerName
}
END{
foreach($comp in $allServers){
Write-Verbose "Processing server '$comp'..."
if(!(Test-Path "\\$comp\c$\windows")){
Write-Warning "ERROR: Failed to connect to server '$comp'"
}
else{
Write-Verbose "Connected to server '$comp'..."
$allusers = $null
$allusers = ([ADSI]"WinNT://$comp").children | ?{$_.SchemaClassName -eq 'user'}
if(!$allusers){
Write-Warning "ERROR: Failed to retrive users from server '$comp'"
}
else{
Write-Verbose "Retrieved user objects from server '$comp'..."
if($allusers){
$selectuser = $allusers |?{$_.name -like $Username}
if($selectuser){
Write-Verbose "Found user '$Username' from server '$comp'..."
try{
$selectuser.SetPassword($Password)
$selectuser.setinfo()
#Other method: $selectuser.psbase.invoke("setpassword",$Password)
Write-Output "$(Get-Date) - Successfully changed password for user '$Username' on server '$comp'"
}
catch{
Write-Warning "ERROR: Unable to set password for user '$Username' on server '$comp'"
}
}
else{
Write-Warning "ERROR: No user '$Username' on server '$Comp'"
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment