none
Powershell script - check if accounts exist in AD (enable/disabled) RRS feed

  • Question

  • Hi all

    Found this script and was wondering if it will do what I want. I have as CSV file  with list of accounts and need to check if they exist in AD and also if they are enabled/disabled. Would be nice if it can be exported as a new CSV file output.


    Thanks in advance all

    ######################################################################################################
    #Validate if the specified account exists in AD
    ######################################################################################################

    #ActiveDirectory Module is been imported to Powershell. 
    Import-Module ActiveDirectory

    $Username=Read-host -prompt "`nPlease enter the user account [domain\account]:"
    $ADServer=Read-host -prompt "`nPlease enter the AD Server name [NetBIOS name]:"
    $ADPort=Read-host -prompt "`nPlease enter the AD port no.:"

    #Using WMI object to retrieve the domain name
    $ADDomainName=(Get-WmiObject Win32_ComputerSystem).Domain

    #Splitting the domain name a.com to a and com
    $D1name=($ADDomainName.Split(".")[0])
    $D2name=($ADDomainName.Split(".")[1])
    write-host("Retrieved the Root AD domain.")

    #Function with LDAP query to check the user account in AD
    Function Check-ADUser 

        Param ($Username) 
     
        $Username = ($Username.Split("\")[1]) 
        $ADCompletePath = "LDAP://"+$ADServer+":"+$ADPort+"/DC="+$D1name+",DC="+$D2name
        $ADRoot =  [ADSI]'"$ADCompletePath"'

        $ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot)  
        $SAMAccountName = "$Username" 
        $ADSearch.Filter = "(&(objectClass=user)(sAMAccountName=$SAMAccountName))" 
        $Result = $ADSearch.FindAll() 
     
        If($Result.Count -eq 0) 
        { 
            $Status = "0" 
        } 
        Else 
        { 
            $Status = "1" 
        } 
         
        $Results = New-Object Psobject 
        $Results | Add-Member Noteproperty Status $Status 
        Write-Output $Results     
    }

    $Status = (Check-ADUser -username $username).Status
    If ($Status -eq 1)
    {
        write-host("$UserName exists.")
    } Else {
        write-host("$UserName does not exists. Please give a valid account.")
        Exit
    }

    Thursday, February 26, 2015 3:07 AM

Answers

  • The script you posted deliver that output, but it also imports the AD module without actually requiring it. Here is a short blurb which matches your requirements more closely. It assumes you have a .csv file with a header named samaccountname of the users you would like to query for. Feel free to edit the code to fit your needs more closely:

    Import-Csv ListofUsers.csv | ForEach-Object {
        New-Object -TypeName PSCustomObject -Property @{
            samaccountname = $_.samaccountname
            exist = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").findone())
            enabled = [bool]($account.properties.useraccountcontrol[0] -band 2)
        }
    } | Export-Csv Output.csv -NoTypeInformation


    Jaap Brasser
    http://www.jaapbrasser.com

    • Proposed as answer by jrv Thursday, February 26, 2015 4:16 AM
    • Marked as answer by Boe ProxMVP, Moderator Sunday, July 26, 2015 3:28 AM
    Thursday, February 26, 2015 3:22 AM
    Moderator

All replies

  • The script you posted deliver that output, but it also imports the AD module without actually requiring it. Here is a short blurb which matches your requirements more closely. It assumes you have a .csv file with a header named samaccountname of the users you would like to query for. Feel free to edit the code to fit your needs more closely:

    Import-Csv ListofUsers.csv | ForEach-Object {
        New-Object -TypeName PSCustomObject -Property @{
            samaccountname = $_.samaccountname
            exist = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").findone())
            enabled = [bool]($account.properties.useraccountcontrol[0] -band 2)
        }
    } | Export-Csv Output.csv -NoTypeInformation


    Jaap Brasser
    http://www.jaapbrasser.com

    • Proposed as answer by jrv Thursday, February 26, 2015 4:16 AM
    • Marked as answer by Boe ProxMVP, Moderator Sunday, July 26, 2015 3:28 AM
    Thursday, February 26, 2015 3:22 AM
    Moderator
  • Getting this error

    Import-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
    "ForEach-Object" to type "System.Char". Error: "String must be exactl
    y one character long."
    At C:\scripts\Userlist.ps1:1 char:11
    + Import-Csv <<<<  ListofUsers.csv  ForEach-Object {
        + CategoryInfo          : InvalidArgument: (:) [Import-Csv], Par
       ameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microso
       ft.PowerShell.Commands.ImportCsvCommand

    Thursday, February 26, 2015 3:55 AM
  • Did you remove the pipeline, |, character by any chance?

    Jaap Brasser
    http://www.jaapbrasser.com

    Thursday, February 26, 2015 10:35 AM
    Moderator
  • Thanks so much that works now.

    Not sure how the character | wasn't added as I copied and paste your code

    I am very new to Powershell and interested to learn more because I use Active Directory quite a bit.

    Are there any good blog/forums to read up besides the one we're on here ? :)

    Thursday, February 26, 2015 7:46 PM
  • I think the Scripting Guy Blog is most active PowerShell blog I am aware of, personally I frequently visit are powershellmagazine.com, powershell.compowershell.org and a number of blogs of PowerShell enthusiasts (Jeff/Boe/Bartek) are a few that spring to mind. Twitter is quite decent to keep up to date with PowerShell stuff, have a look at #PowerShell you will see plenty of content flying around. 

    I think if you really want to learn more having a good foundation is what really helps and I believe reading a book is a good method of getting a good foundation. The Scripting Guy, Ed Wilson, has written many easy to digest books that will give you a good foundation for further developing your PowerShell skills. For example Windows PowerShell Best Practices. Another personal favorite of mine is the older PowerShell in Action by Bruce Payette, but it is occasionally a bit of a deep dive and I would not recommend it as a first book.

    I think frequenting forums and seeing how other people are using PowerShell and to see the issues they are running into is a great way to learn as well. And if you see something you actually know the answer to you might be able to help someone out yourself. I learned a lot just by being active on forums and seeing how experts applied their knowledge of PowerShell to every problems.

    Depending on your area you could join (or even start!) a local or virtual PowerShell community, there are dozens of communities which frequently hold either offline or online meetings in which new concepts are discussed. For an overview you can have a look at powershellgroup.org, or simply type in the name of you city/state or country in your favorite search engine to find any groups nearby.

    If you are ready to be overwhelmed by content you check out this entry on the Technet Wiki, it lists most PowerShell, it is appropriately called Windows PowerShell Survival Guide or 'the article formerly known as Automating IT Tasks with Windows PowerShell Overview'. This article contains most of the community blogs, book suggestions, forums, technical resources or to summarize pretty much everything that can be found regarding PowerShell.

    Well this post became slightly longer than intended, but hopefully it will help you out on your path to become a PowerShell wizard ;) Happy scripting valantism.


    Jaap Brasser
    http://www.jaapbrasser.com


    Friday, February 27, 2015 5:26 AM
    Moderator
  • Hi Jaap / Everyone,

    This solution only works for me if the user accounts do exist in AD. In this case a csv file is generated and contains the required information.

    If an account does not exist in AD, Powershell will throw the message below. In this case a csv file is generated and contains only the accounts which are present in AD.

    How can I change the script so that the output clearly specifies whether or not an account is present in AD?

    PowerShell Message:

    Cannot index into a null array.

    At line:4 char:59
    + exist = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))"). ...
    +                                                           ~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : NullArray


    Saturday, June 17, 2017 4:32 PM
  • Did you get a response on this at all - im seeing the same exact issue. 

    I noticed this;

    Original:
    enabled = [bool]($account.properties.useraccountcontrol[0] -band 2)

    So what they're saying there is "I want this to say true to being enabled if 2(disabled) = 2". But as we know, when it's enabled, it's actually zero!

    Simple fix - change it to this, if you just want to change the name :)
    Disabled = [bool]($account.properties.useraccountcontrol[0] -band 2)

    if you want to keep the name as "Enabled", then you have to do a further test and actually compare it to zero

    enabled = [bool]($account.properties.useraccountcontrol[0] -band 2) -eq 0

    However i still get an error in PS and no output whatsoever

    Friday, December 1, 2017 2:12 PM
  • I think the Scripting Guy Blog is most active PowerShell blog I am aware of, personally I frequently visit are powershellmagazine.com, powershell.compowershell.org and a number of blogs of PowerShell enthusiasts (Jeff/Boe/Bartek) are a few that spring to mind. Twitter is quite decent to keep up to date with PowerShell stuff, have a look at #PowerShell you will see plenty of content flying around. 

    I think if you really want to learn more having a good foundation is what really helps and I believe reading a book is a good method of getting a good foundation. The Scripting Guy, Ed Wilson, has written many easy to digest books that will give you a good foundation for further developing your PowerShell skills. For example Windows PowerShell Best Practices. Another personal favorite of mine is the older PowerShell in Action by Bruce Payette, but it is occasionally a bit of a deep dive and I would not recommend it as a first book.

    I think frequenting forums and seeing how other people are using PowerShell and to see the issues they are running into is a great way to learn as well. And if you see something you actually know the answer to you might be able to help someone out yourself. I learned a lot just by being active on forums and seeing how experts applied their knowledge of PowerShell to every problems.

    Depending on your area you could join (or even start!) a local or virtual PowerShell community, there are dozens of communities which frequently hold either offline or online meetings in which new concepts are discussed. For an overview you can have a look at powershellgroup.org, or simply type in the name of you city/state or country in your favorite search engine to find any groups nearby.

    If you are ready to be overwhelmed by content you check out this entry on the Technet Wiki, it lists most PowerShell, it is appropriately called Windows PowerShell Survival Guide or 'the article formerly known as Automating IT Tasks with Windows PowerShell Overview'. This article contains most of the community blogs, book suggestions, forums, technical resources or to summarize pretty much everything that can be found regarding PowerShell.

    Well this post became slightly longer than intended, but hopefully it will help you out on your path to become a PowerShell wizard ;) Happy scripting valantism.


    Jaap Brasser
    http://www.jaapbrasser.com


    IT is longer, but helpful JAAP....Thanks

    Saturday, December 2, 2017 5:28 AM