powershelldnsdirectorycommandlocked

Command to Unlock a locked domain user


I'v been using these to list locked users in my domain and prompt me for input samaccountname to unlock desired one: I did it with 3 file.

first one is ps1 to list all of them

    import-module activedirectory
    search-adaccount -lockedout | select  name, samaccountname, OU

second one is another ps1 file:

    $user = Read-Host "Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list"
    Search-ADAccount -LockedOut | Where {$_.samaccountname -eq $user} | Unlock-ADAccount

and for executing above files, i use a .bat file:

    :loop
    powershell.exe -ExecutionPolicy Bypass -File c:\ps\lockedlist.ps1
    powershell.exe -ExecutionPolicy Bypass -File c:\ps\unlock.ps1
    cls
    goto loop

and when i run it... it list all locked users and i can copy paste each samaacount name to unlock them

BUT the problem is,when I want to do it with ONE ps1 file it doesnt work. it just ask for samaccountname but it doesnt list it

    import-module activedirectory
    search-adaccount -lockedout | select  name, samaccountname, OU
    $user = Read-Host "Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list"
    Search-ADAccount -LockedOut | Where {$_.samaccountname -eq $user} | Unlock-ADAccount

i know .bat file will be pretty same...

thanks to anyone who reads and helps.


Solution

  • Powershell always tries to optimize the output it gives for you. So the order of the output might not be the same as you expect it from the commands you have in a script. If possible it will concatenate output to be more readable especially when it's the same type of objects. To break this you could use a format cmdlet like Format-Table par example.

    Search-ADAccount -LockedOut | 
        Select-Object -Property Name, sAMAccountName, DistinguishedName |
            Format-Table
    $user = Read-Host -Prompt 'Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list'
    Search-ADAccount -LockedOut | 
        Where-Object -FilterScript {$_.samaccountname -eq $user} | 
            Unlock-ADAccount
    

    At least, it worked in my environment. And BTW: Since Powershell version 3 you don't need to explicitly import the modules anymore. They will be imported automaticaly. Better would be to use a #Requires statement like #Requires -Modules activedirectory on top of the script. That would even prevent the script to run if there's no active directory module installed