Skip to content

Instantly share code, notes, and snippets.

@rstolpe
Created June 29, 2022 17:21
Show Gist options
  • Save rstolpe/f6444a9e9ad19e4f060a7c1e4aace092 to your computer and use it in GitHub Desktop.
Save rstolpe/f6444a9e9ad19e4f060a7c1e4aace092 to your computer and use it in GitHub Desktop.
Unlock AD Account
Function Unlock-ADAccounts {
#[CmdletBinding()]
#Param(
# [Parameter(Mandatory = $true)][array]$UserNames =
#)
[string]$UserNames = Read-Host -Prompt "What users do you want to check? (separate the users with ,)"
[array]$UserNames = $UserNames -split ","
# Checks if the Active Directory module are loaded if it's not then it imports it.
if (-Not(Get-Module -ListAvailable -Name "ActiveDirectory")) {
try {
Import-Module -Name "ActiveDirectory"
}
catch {
write-Host "Could not import the active directory module"
Write-Host "$($PSItem.Exception)"
break
}
}
foreach ($User in $UserNames) {
# Checks if the AD Account exists
$CheckADAccount = $(try { Get-ADUser -Filter "Samaccountname -eq '$($User)'" -properties SamAccountName } catch { $null })
if ($Null -ne $CheckADAccount) {
# Get locked status from the AD Account
$ADuser = Get-ADUser -Filter "samaccountname -eq '$($User)'" -Properties LockedOut, SamAccountName
# IF the AD account are locked the following are happening
if ($ADuser.LockedOut -eq $true) {
# Unlockes the account but it also catches if something goes wrong, but it still continues.
try {
Unlock-ADAccount -Identity $ADuser.samaccountname -Confirm:$false
write-host "The account $($ADuser.samaccountname) has now been unlocked"
}
catch {
Write-Host "$($PSItem.Exception)"
return
}
}
else {
Write-Host "The account $($ADuser.samaccountname) was not locked, did not do anything"
}
}
else {
Write-Host "The account $($User) don't exists in the AD!"
}
}
}
#So after you have pasted this module or just copy pasted it in to PowerShell you just write the following, and when it asks after value for the -UserNames separate it with ,
Unlock-ADAccounts -FromFile $false -UserNames
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment