Skip to content

Instantly share code, notes, and snippets.

@rodmhgl
Last active July 12, 2017 23:41
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 rodmhgl/243c0915a5672cf90f34b7a42cd8e66c to your computer and use it in GitHub Desktop.
Save rodmhgl/243c0915a5672cf90f34b7a42cd8e66c to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
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
Copy link

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