Powershell unlock and reset AD account
Recently I found a nice script from Matt Schmit. This script give you the choice to reset a users password, unlock a account and has some nice error checking and a good structure.
Powershell unlock and reset AD account
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
<# Author: Matt Schmitt Date: 12/4/12 Version: 2.0 From: USA Email: ithink2020@gmail.com Website: http://about.me/schmittmatt Twitter: @MatthewASchmitt Description A tool checking for Locked Accounts in AD, checking if a user is locked out, unlocking the user's account and for resetting a user's password. UPDATED 12/11/12 Added some Error Handling Check if server is available. If not, skip sever and do not try to exicute code on it. Changed the way I handled the $servers array. This is so I can remove a server if it is unavailable. Check if supplied user is in AD. If not, Ask the admin to re-enter username Added Comment blocks for each section. UPDATED 12/10/12 Added the use of functions to clean up repeated code. Cleaned up Password reset code to use a foreach that looks at the $servers array. Added some needed Comments UPDATED 12/4/12 Cleaned up Checking LockedOut Status code - replaced with foreach statement that looks at $Servers array Cleaned up Unlock code - replaced with foreach statement that looks at $Servers array Cleaned up Get pwdlastset date - rewrote to use the method I was using for other lookups for AD properties. #> #Imports Active Directory Module Import-Module -ModuleInfo ActiveDirectory Write-Host -object "" Write-Host -object "PowerShell AD Password Tool" Write-Host -object "" Write-Host -object "This tool displays the Exparation Date of a user's Password and thier Lockedout" Write-Host -object "Status. It will then allow you to unlock and/or reset the password." Write-Host -object "" Write-Host -object "" ########################### ## FUNCTIONS ## ########################### ################################# ### unlockAndCheck function ### ################################# #This fuction unlocks defined user account on the DCs defined in the $servers array, then checks the #local DC to make sure it did get unlocked. function unlockAndCheck { foreach ($server in $servers) { Try { Write-Host -object "Unlocking account on $server" Unlock-ADAccount -Identity $user -server $server }catch{ } } #Get Lockedout status and set it to $Lock $Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) Write-Host -object "" #Depending on Status, tell user if the account is locked or not. switch ($Lock) { "False" { Write-Host -object "$user is unlocked." } "True" { Write-Host -Object "$user is LOCKED Out." } } } ############################ ### resetPass function ### ############################ #This function resets the password for the defined user on the DCs define in the $server array. function resetPass { $newpass = (Read-Host -AsSecureString "Enter user's New Password") foreach ($server in $servers) { Write-Host -Object "Resetting Password on $server" Set-ADAccountPassword -Server $server -Identity $user -NewPassword $newpass } Write-Host -Object "" Write-Host -Object "Password for $user has been reset." Write-Host -Object "" } ########################### ## End FUNCTIONS ## ########################### ########################### ## Define DCs to use ## ########################### <# For our company we have several DCs across the globe. Since the DCs at each site update each other farely quickly, I'm only going to define one DC per site. This will save time in checking the lockedOUt status, unlocking the user and resetting the password. ---> IMPORTANT: Update $servers array list as DCs change!!! #> #Creating Empty $servers Array $servers = New-Object System.Collections.ArrayList #Creating Empty $unavailable Array $unavailable = New-Object System.Collections.ArrayList #Assign Domain Controllers to $servers Array $servers.add("DC01.your.domain.com") | out-null $servers.add("DC02.your.domain.com") | out-null # NOTE: can can add more, just add them idividually like I did above. ################################################## ## Check for Any Locked User Accounts in AD ## ################################################## #Counts how many locked account there are on the local DC and sets it to $count $count = Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Measure-Object | Select-Object -expand Count #If there are locked accounts (other than Administrator and Guest), then this will display who is locked out. If ( $count -gt 0 ) { Write-Host "Current Locked Out Accounts on your LOCAL Domain Controller:" Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Select-Object Name, @{Expression={$_.SamAccountName};Label="Username"},@{Expression={$_.physicalDeliveryOfficeName};Label="Office Location"},@{Expression={$_.TelephoneNumber};Label="Phone Number"},@{Expression={$_.LastLogonDate};Label="Last Logon Date"} | Format-Table -AutoSize }else{ # Write-Host "There are no locked out accounts on your local Domain Controller." } Write-Host -Object "" ###################################### ## Ask for Username and Validate ## ###################################### #Asks for the username $user = Read-Host "Enter username of the employee you would like to check or [ Ctrl+c ] to exit" [int]$Checker1 = 0 # ERROR CHECKING Do { # Try to retrieve info for given user, catch error if unalbe to retrieve Try { # Attempt to retrieve info about user and suppress output Get-ADUser -Identity $user | Out-Null # If successful, set Checker to 1 to exi do loop. $Checker1 = 1 }catch{ # If Attempt to retrieve info fails, run code in this catch block #Username entered was not found. Have user try again. cls Write-Host -Object "" Write-Host -Object "" Write-Host -Object "Username not found! - Please try again." -BackgroundColor Red -ForegroundColor White Write-Host -Object "" $user = Read-Host "Enter username of the employee you would like to check or [ Ctrl+c ] to exit" } # If Checker1 is equal to zero, then redo Do loop. }While ($Checker1 -eq 0) ############################################################# ## Get and display user's Display Name and Phone Number ## ############################################################# #Once a valid user is entered, proceed with remaining code cls Write-Host -object "" Write-Host "" # Gets Display name of entered user $Name = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand DisplayName) # Gets Phone number of entered user $phone = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand telephoneNumber) # Displays the Display Name and Phone number of user - I use this to verify I have the correct user and # to have the phone number available, if I need to contact the user. Write-Host -Object "$Name's phone number is: $phone" Write-Host -Object "" Write-Host -Object "" #################################### ## Get and Check Password Age ## #################################### # Get today's date [datetime]$today = (get-date) #Get pwdlastset date from AD and set it to $passdate2 $passdate2 = [datetime]::fromfiletime((Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand pwdlastset)) #calculate Password age in days $PwdAge = ($today - $passdate2).Days #check if password is over 90 days old If ($PwdAge -gt 90){ # If password is over 90 days old, let admin know it is expired and show password age Write-Host -Object "Password for $user is EXPIRED!" Write-Host -Object "Password for $user is $PwdAge days old." }else{ # If password is under 90, just display age Write-Host -Object "Password for $user is $PwdAge days old." } Write-Host -Object "" Write-Host -Object "" ######################################################## ## user Lockedout status on each available server ## ######################################################## #Get Check server availablity, then check user Lockedout status on each available server foreach ($object in $servers) { # ERROR CHECKING Try{ # Check to see if server is available via a ping ping $object -n 1 | Out-Null # If server is available, complete code: switch (Get-ADUser -server $object -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"$object `t `t Not Locked"} "True" {"$object `t `t LOCKED"} } }catch{ # If server is not available, alert admin that it will be skipped. Write-host -Object "$object `t `t NOT Found - Skipping" -ForegroundColor white -BackgroundColor red # Add unavailible server to $unavailible array $unavailable.add($object) | out-null } } ################################ ## $servers Array Cleanup ## ################################ <# For each server that is unavailible, remove from $servers array The reason for this is so the unlockAndCheck & the resetPass function do not try to exicute thier code on the servers that are not available. A little bit of error handling. #> foreach ($server in $unavailable){ $servers.Remove($server) } ############################################## ## Ask Admin what they would like to do ## ############################################## Write-Host -Object "" Write-Host -Object "" $option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, ` (3) Unlock and reset user's password or (4) Exit?" ################################ ## Carryout Selected Task ## ################################ cls [int]$checker2 = 0 While ($checker2 -eq 0) { switch ($option){ "1" { #Call unlockAndCheck Function unlockAndCheck Write-Host -Object "" Write-Host -Object "Press any key to Exit." $checker2 += 5 $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } "2" { #call resetPass function resetPass Write-Host -Object "" Write-Host -Object "Press any key to Exit." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $checker2 += 5 } "3" { #call resetPass function resetPass #Call unlockAndCheck Function unlockAndCheck Write-Host -Object "" Write-Host -Object "Press any key to Exit." $checker2 += 5 $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } "4" { #exit code $checker2 += 5 } default { Write-Host -Object "" Write-Host -Object "" Write-Host -Object "You have entered an incorrect number." -BackgroundColor Red -ForegroundColor White Write-Host -Object "" $option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?" } } } |