Avatar of IT_Support Private
IT_Support Private
 asked on

Query - Powershell Script formatting for Unlock single AD User Account

Hi All,

I have the below working script, though would like to pick some experts brains please.

A)Is there anything wrong, i.e, can I cause harm/damage if I am running the "Unlock-AD" if the actual account isn't even locked?

eg, should it include something like - If Username is locked, then Unlock?

B)Is the below formatting OK, or is there a better "Preferred/Recommended" way I should be using?

C)As I work in 1st/2nd Line Support I often get calls for AD unlocks, any other suggestions I should be running this script to make it more efficient

eg, does anyone use a script to search for surname and first name to pick up female name changes etc instead of by username or how else do others do their environment?

Thanks,

Import-Module ActiveDirectory

$Credentials = Get-Credential $UserName = Read-Host "Enter in the Username to check"

Get-ADUser $UserName -Properties Displayname, LockedOut, badPwdCount, AccountLockoutTime, PasswordExpired `
| Select-Object -Property Displayname, LockedOut, badPwdCount, AccountLockoutTime, PasswordExpired

Unlock-ADAccount $UserName -Credential $Credentials

Open in new window

PowershellActive Directory

Avatar of undefined
Last Comment
Shaun Vermaak

8/22/2022 - Mon
David Johnson, CD

If it is not locked then unlocking doesn't do anything
Jose Gabriel Ortega Castro

David answered A.

What about making it a real script.
[Cmdletbinding()]
param(
    [Parameter(mandatory=$true,Position=0)]$username
)

Import-Module ActiveDirectory
Get-ADUser $UserName  | Unlock-ADAccount

Open in new window


Save it as Unlocker.ps1

And run it like:
.\Unlocker.ps1 -username "UserNameToUnlock"

You won't require credentials if you're a domain admin.
If you don't you would require it. so...

[Cmdletbinding()]
param(
    [Parameter(mandatory=$true,Position=0)]$username
)
$creds = Get-Credential
Import-Module ActiveDirectory
Get-ADUser $UserName  | Unlock-ADAccount -credential $creds

Open in new window

ASKER CERTIFIED SOLUTION
MilesLogan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
IT_Support Private

ASKER
Thanks all for the advice. Much appreciated.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Shaun Vermaak

I added unlock option to my Password Reset Tool if you would like to test it
https://www.experts-exchange.com/articles/30866/Active-Directory-Password-Reset-Tool.html