Home > database >  powershell ask to unlock user in AD
powershell ask to unlock user in AD

Time:11-10

not an expert in PowerShell but learning none the less. I found 2 lines or 2 commands which could really help my job get done faster.

The goal would be to use the PowerShell to unlock a user and if it is locked, unlock it and I'm done. very simple.

How would I do that though. The logic behind it would be this:

  • SHOW if user is locked
    • IF user is locked
      • THEN unlock
    • ELSE exit

Those 2 lines that I use is this :

Unlock-ADAccount -Identity "usernamehere"
Get-ADUser -Identity 'usernamehere' -Properties LockedOut | Select-Object Name, Lockedout

I know I can use the Read-Host to get some input from the user but that's where it stops for me though.

Best I could come up with is this:

$user = read-host -prompt 'Enter Username'
$lockedout = get-aduser $user -property lockedout | foreach { $_.LockedOut }
Write-Output "Account Locked: $($LockedOut)"

but it doesn't ask if I want to unlock

CodePudding user response:

Inline comments should help you understand the logic of the code. PSHostUserInterface.PromptForChoice method is nice for this kind of things, this method will allow you to prompt user input with additional help messages and will also validate user input, meaning, the user must provide the right input (Y or N).

$query = Read-Host -Prompt 'Enter Username'
$adUsr = Get-ADUser $user -Properties LockedOut
# if the user is locked
if($adUsr.LockedOut) {
    # what do we do here?
    $choice = $ExecutionContext.Host.UI.PromptForChoice(
        'Locked User',
        ('"{0}" is locked, would you like to unlock it?' -f $adUsr.SamAccountName),
        ('&Yes', '&No'),
        0 # => Default choice is `Yes`
    )
    # if choice was `Yes`
    if($choice -eq 0) {
        '"{0}" was sucessfully unlocked.' -f $adUsr.SamAccountName
    }
    # user was locked but it was decided to not unlock it
    else {
        # you can decide what to do here
    }
}
# else, if the user is not locked
else {
    '"{0}" is not locked. Goodbye.' -f $adUsr.SamAccountName
}
  • Related