Skip to content

Instantly share code, notes, and snippets.

@rodmhgl rodmhgl/Reset-Password.ps1
Last active Jul 12, 2017

Embed
What would you like to do?
For James Espinoza - Help Desk script to reset user's password
[cmdletbinding()]
param(
# Give the user the opton to user a -User command line parameter
[string]$User = $(Read-Host "Enter a samAccountName")
)
# Show $User details on console
# Consider which properties you actually need
# Using * is a memory hog and unnecesary
try {
$UserObject = Get-ADUser -Identity $User -Server adVM -Properties EmployeeNumber -ErrorAction Stop
# Use Out-Host to work around issue with Read-Host swallowing the output
$UserObject | Select Name, samAccountName, EmployeeNumber, Enabled | Out-Host
} catch {
Write-Error "Error encountered locating user: $($_)"
Exit
}
# Verify $User is not empty and reset the password with a secure string prompt
# if $User exists, it will return true, no need to compare to $null
If ($UserObject) {
try {
$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
# We went through all the trouble of pulling the user object above, may as well use it
$UserObject | Set-ADAccountPassword -NewPassword $newpassword -Reset -ErrorAction Stop
} catch {
Write-Error "Error encountered setting password: $($_)"
Exit
}
}
@poshcodebear

This comment has been minimized.

Copy link

poshcodebear commented Jul 12, 2017

Two things to note here: -ErrorAction Stop doesn't work correctly for Get-ADUser, and will never trigger the catch to fire. That's why I recommended using -Filter in the Facebook post ;)

The other is, there's no reason to use Sort-Object since you should only ever get back 1 result; if you got back more, there would be a problem.

@rodmhgl

This comment has been minimized.

Copy link
Owner Author

rodmhgl commented Jul 12, 2017

I agree on Sort-Object, meant to remove that. I am able to trigger the Catch though:

PS C:\Users\rnadmin> C:\Users\rnadmin\userpass.ps1
Enter a samAccountName: FakeUser
C:\Users\rnadmin\userpass.ps1 : Error encountered locating user: Cannot find an object with identity: 'FakeUser' under: 'DC=lab,DC=local'.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,userpass.ps1

@poshcodebear

This comment has been minimized.

Copy link

poshcodebear commented Jul 12, 2017

Huh...I've never had that work before. It's working for me now, though.

Then again, I've never tested it directly from the DC before, so it may just be an issue when going through remoting. I'll have to set up another machine to test that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.