Unlock User Function

Hello All,

Like many of you I got tired of clicking through ADUG snapins to unlock users (as some days are worse than others). So I wrote a quick little function and added it into my profile to save some time. I work in the finance industry so for compliance I had to make sure I was only unlocking a single user account. The colors on the elseif were added just for fun, but I wanted to see if anyone had any better ideas as I still have a lot to learn when it comes to scripting and PowerShell.


Hi Mike.

It’s looks good. You could also allow it to accept pipeline input and maybe even use an alias to give it extra flexibility. If you return a psobject, you can then also use this output with another function in a pipeline.

I’ve not checked the code below 100%, but this is a type of template of how you could add this.

function Unlock-Me
        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True,HelpMessage = 'Enter SamAccountName of user to unlock')][Alias('your alias')][String]$UserName
     $users = Search-ADAccount -LockedOut | Where-Object  -Property SamAccountName -Match  -Value $UserName
     $status = 'Not found'
    if($users.SamAccountName -match "$UserName")
      Unlock-ADAccount $UserName -Verbose
      $status = 'Unlocked'
    elseif($users.SamAccountName -inotmatch "$UserName")
      $host.ui.RawUI.ForegroundColor = 'Green'
      "$UserName is not locked out"
       $host.ui.RawUI.ForegroundColor = 'DarkYellow'
       $status = 'Not Locked'
        $hash = @{
            Username = $UserName
            Status = $status

        New-Object -TypeName PsObject -Property $hash