Pickle
Pickle

Reputation: 1124

Powershell script to check if account is enabled from CSV file

I have a list of about 1000 usernames in a CSV file and I need to check if they are enabled or not. I can't seem to find a tutorial on how to do this without using a third-party snapin, which isn't an option.

It seems like this should be a rather simple script, but I can't seem to get it right.

function Test-UserAccountDisabled
{
     param($account)
     $searcher = new-object System.DirectoryServices.DirectorySearcher
     $searcher.filter = "(sAMAccountName=$Account)"
     $user=$searcher.FindOne().GetDirectoryEntry()
     if($($user.userAccountControl) -band 0x2){$true}else{$false}
}

$file = Select-FileDialog -Title "Select a file" -Directory "C:\" -Filter "All Files (*.*)|*.*"

$users = Import-Csv $file

foreach($account in $users)
{
  Test-UserAccountDisabled($account)
}

It returns with "You cannot call a method on a null-valued expression." What am I doing wrong here?

Upvotes: 1

Views: 19298

Answers (2)

Shay Levy
Shay Levy

Reputation: 126912

What's in $Account?

Assuming the CSV file contains a SamAccountName column:

Import-Csv $file | Foreach-Object{

    $user = ([ADSISEARCHER]"(samaccountname=$($_.SamAccountName))").FindOne()

    if($user)
    {
        New-Object -TypeName PSObject -Property @{
            SamAccountName = $user.SamAccountName
            IsDisabled = $user.GetDirectoryEntry().InvokeGet('AccountDisabled')
        }
    }
    else
    {
            Write-Warning "Can't find user '$($_.SamAccountName)'"
    }
}

Upvotes: 3

Aaron Jensen
Aaron Jensen

Reputation: 26799

As commenter latkin mentioned, it looks like you're calling Test-UserAccountDisabled like a C#-style function. Parenthesis mean arrays or expressions in PowerShell. Change

Test-UserAccountDisabled ($account)

to

Test-UserAccountDisabled $account

If that still doesn't solve the problem, please let us know what line number the error is happening on.

Upvotes: 0

Related Questions