Home » Blog » Active Directory » Unlock AD Account with PowerShell Scripts & Reset Account Access

Unlock AD Account with PowerShell Scripts & Reset Account Access

author
Published By siddharth
Anuraag Singh
Approved By Anuraag Singh
Published On June 27th, 2024
Reading Time 9 Minutes Reading
Category Active Directory

Whenever users face access denial issues, their first instinct is to ask the admin to unlock their AD account with PowerShell scripts. Although a user’s job may end after raising a request, for the admin, this is just the start. They are the ones who have to sort out the confusing account status setup and filter out genuine locked users from the ones that have been disabled manually
This task is quite challenging, especially for those admins who are not well-versed in PowerShell. Not to mention, even veteran administrators have expressed confusion regarding the status naming scheme that AD uses. So let’s learn to distinguish between locked, inactive, disabled, deleted, and expired account types.

Before We Unlock AD Account with PowerShell Read This

Many times when admins want to unlock user accounts with PowerShell or otherwise, they often find it hard to keep track of the account. As many of the statuses sound similar but have different data retention and recovery polices. So to clear out the differences here is a tabular construction

 

Parameter Locked Inactive Disabled Deleted Expired
Description The user account is temporarily inaccessible due to exceeding incorrect login attempts or administrator intervention. A user account remains active, but not in use for a period of time. Administrator(s) deliberately disable user account(s) to prevent login. The user account is permanently removed from Active Directory. The password associated with the account has reached its expiration date set by the administrator.
Can Users  Log In No Potentially (depending on the reason for inactivity) No N/A No
Requires Administrator Action Yes (to unlock) No Yes (to enable) Not Typically No (password reset might be needed)
Account Still Exists in AD Yes Yes Yes/No (Organization Rules) No Yes (until purged)
Data Wiped Out No Policy Dependent No Yes No
Typically Caused by – Repeated failed login attempts. – Security measure by administrator. – User on leave or long-term absence. – Seasonal employees. – Terminated employee. – Contractor access revoked. – Removing unused accounts for security and efficiency. – Enforcing password changes at regular intervals.

 

Now we hope admins have no problem figuring out when to find inactive computers in Active Directory from other requirements like unlocking. So let’s see what preparation one has to make before regaining account access.

Prerequisites to Unlock AD Accounts with PowerShell Scripts

Locked Account recovery is one of the high-priority tasks that administrators need to complete at once. The alternative is losing countless user productivity hours. No organization can afford to fall behind due to a trivial problem like being locked out.

Moreover, having a regular reporting mechanism can help administrators understand which users are more prone to getting their accounts locked out.
Here is a small list of prerequisites that need to be completed before you can go forward with the regular task.

  • First is using the RSAT make sure that you have the Active Directory Module installed and running.
  • Second, check that PowerShell is updated to the latest version supported by your Windows desktop or Server OS.

How to Unlock AD Account with PowerShell Quickly

Open a new PowerShell module and type:

Get-ADUser -Filter * -Properties LockedOut | Where-Object { $_.LockedOut -eq $true }

This displays all those accounts that are locked. Don’t worry if you can’t see an output or notification right away. It just means that in the current domain, all users have access to the accounts. so change the domain open a new PowerShell module and use the same cmdlet.

Copy the distinguished name and  paste it alongside the following command to change the lockout status:

Unlock-ADAccount -Identity "CN=Dummy DU22. User22,OU=New Users,DC=cu14mail,DC=local"

Ensure that you type the user name correctly or you may get an error or invalid results. Reuse the first cmdlet to verify the change.

PowerShell cmdlet

Sometimes administrators may be in a situation where a mass lockout has happened. In such a case, it is not wise to unlock each account one by one. A better way would be to deploy an AD-wide script that resets account access all at once.

PowerShell Scripts to Unlock AD Accounts in Bulk

Search-ADAccount -LockedOut -UsersOnly | Unlock-ADAccount -Confirm

The above cmdlet combines the search filter with the unlock operation by restricting the scope to all locked accounts. Moreover, by adding the confirm parameter, you can trigger an individual level of yes or no criteria. If you know that the locked accounts are few and were due to some erroneous result, you can omit the “-Confirm” parameter from the cmdlet altogether.

The problem with this cmdlet is that admins have to type it out every time manually. To automate account unlocking, we take help from an in-built Microsoft utility, i.e., the Task Scheduler application.

First, we are going to make a custom script that unlocks the user account:

# Import the ActiveDirectory module
Import-Module ActiveDirectory

# Function to unlock locked user accounts
function Unlock-LockedAccounts {
# Get all locked user accounts
$lockedAccounts = Search-ADAccount -LockedOut -UsersOnly

if ($lockedAccounts.Count -eq 0) {
Write-Output "No locked user accounts found."
return
}

# Loop through each locked account and unlock it
foreach ($account in $lockedAccounts) {
try {
Unlock-ADAccount -Identity $account
Write-Output "Unlocked account: $($account.SamAccountName)"
} catch {
Write-Output "Failed to unlock account: $($account.SamAccountName). Error: $_"
}
}
}

# Call the function to unlock locked accounts
Unlock-LockedAccounts

Unlock AD Account With PowerShell

Next, use a different set of PowerShell commands to create a scheduled task that starts running the first script without admin intervention.

# Path to the script to be scheduled
$scriptPath = "C:\Users\Administrator\Documents\UnlockAccounts.ps1"

# Task name
$taskName = "UnlockADAccounts"

# Task action
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`""

# Task trigger (every 15 minutes)
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).DateTime -RepetitionInterval (New-TimeSpan -Minutes 1)
# Task settings
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -DontStopOnIdleEnd -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)

# Register the scheduled task
Register-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -TaskName $taskName -Description "Unlock locked Active Directory user accounts every minute"

Write-Output "Scheduled task '$taskName' created to run '$scriptPath' every minute."

Schedule Auto Unlocking

Moreover, it is always best practice to reset user passwords in Active Directory after a bulk unlocking event. Create a new password policy and add all frequent lockout users to that policy. Using PowerShell to unlock accounts is fine but the administrator can’t rely on the scripts for a simple check. More often than not, administrators need to keep a record of lockouts in CSV format.

This PowerShell script is currently missing that feature so admins have to rely on their own wit to add that capability. However, as the PowerShell script is already too complex, it may lead to unintended consequences. So for all reporting purposes, admins can rely on a tried-and-tested utility instead.

Automated Solution to List Locked AD User Accounts

The SysTools Active Directory Reporting Software comes with advanced filtering options to pick and pull the locked account from the rest of the users. It shows the time and arranges the accounts depending on their lockout duration.

Moreover, you always have the option to verify the lock unlock change with the help of the tool described earlier. This is because all AD updates happen in real-time; therefore, the tool automatically replicates the latest change and shows you the results accordingly.

When these smart grouping options combine with the easy-to-navigate UI, any admin can list the data in record time.

Download Now Purchase Now

As a result, admins should have no trouble getting familiar with the tool. For any doubts, we have the tutorial arranged for you as well.

  • Open the tool with the auto-filled credentials (administrator).
    Type administrator
  • Hit the REGISTER DOMAIN CONTROLLER button.
    Register Domain Controller button
  • Fill in your Domain friendly name and the correct IP address in the space provided. Then hit the save and continue button.
    browse-pdf-file
  • The domain details page is where you have to fill in the admin-level credentials, i.e. the email ID and password.
    Save Credentials
  • After that, move to the Report page and select the Locked category under the user workload.
    User
  • If you want you can set the duration by choosing any one of the six different time spans allocated in the duration dropdown. Otherwise, if you want there is a custom filter too.
    preset time intervals
  • Press the preview button to see for which accounts you have to use PowerShell commands to unlock accessibility.
    Preview
  • Hit Download and Select CSV to get the list
    Download CSV

Conclusion

Every admin looking for a way to unlock found their answer in this blog. It doesn’t matter if administrators want to give access back to one account or multiple accounts; the solutions discussed here work for every scenario. Moreover, before unlocking admins should have Apart from the scripts, we gave the tools to identify locked accounts and also explained the distinction between the different account statuses.

Frequently Asked Questions

Q. What is the PowerShell cmdlet that can Unlock a User Account?
There is a simple cmdlet called Unlock-ADAccount. Along with it type the user name (or other object-identifying property like DN).

Q. Some users get locked out of their accounts repeatedly how can I automate the unlocking process?
You can use Task Scheduler (Register-ScheduledTask cmdlet) alongside the usual PowerShell and make a self-unlocking script. Not that depending on the settings Admin workstation must be online for the script to work.

Q. Are there any precautions that I as an admin need to take when I set an auto-unlock task?

Yes, there is a list of practices that need to be followed:

  • First, endure security. Unlocking accounts indiscriminately can be a security risk. So use filters to only unlock those accounts that have a genuine user request.
  • Keep the frequency with which account lockout checks occur in balance. Having checks that are too close or too far apart may be detrimental.
  • Add your own custom error-handling scenarios to the PowerShell script.

 

Connect With Us

+9111-28084986