Slaine MacRoth
Slaine MacRoth

Reputation: 41

Powershell Search AD via CSV and report on disabled / enable / non-existant users

The script below has a CSV input with a column samaccountname and a list of users. When ran it generates a CSV report with 3 columns:

If run in its present state it does indeed generate a report on whether the account is disabled and if it does exist, however if it encounters a user that does not exist in AD they are not added to the CSV report and the following error for each user is thrown:

Cannot index into a null array. At line:4 char:75 + ... ($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").fin ... + ~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray

Is it possible instead for the non-existent users to be added to the CSV report under the column account exists with a value of FALSE

Import-CSV C:\ScriptRepository\Users.csv | ForEach-Object {
    New-Object -TypeName PSCustomObject -Property @{
        samaccountname = $_.samaccountname
        AccountExists = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").findone()).count
        AccountDisabled = [bool]($account.properties.useraccountcontrol[0] -band 2)
    }
} | Export-Csv C:\ScriptRepository\UsersState.csv -NoTypeInformation

Upvotes: 1

Views: 878

Answers (2)

Mark Wragg
Mark Wragg

Reputation: 23395

You could do this by moving the logic to before the hashtable:

Import-CSV C:\ScriptRepository\Users.csv | ForEach-Object {
    $AccountExists = If ( (([adsisearcher]"(samaccountname=$($_.samaccountname))").FindOne()) ) { $true } else { $false }
    If ($AccountExists) { $AccountDisabled = [bool]($AccountExists.properties.useraccountcontrol[0] -band 2) } Else { $AccountDisabled = '' }

    New-Object -TypeName PSCustomObject -Property @{
        samaccountname = $_.samaccountname
        AccountExists = $AccountExists
        AccountDisabled = $AccountDisabled
    }
} | Export-Csv C:\ScriptRepository\UsersState.csv -NoTypeInformation

Upvotes: 0

Bill_Stewart
Bill_Stewart

Reputation: 24585

Here's how I'd handle it:

$ADS_UF_ACCOUNTDISABLE = 2

$searcher = [ADSISearcher] ""
$searcher.PropertiesToLoad.AddRange(@("userAccountControl"))

Import-Csv "Users.csv" | ForEach-Object {
  $searcher.Filter = "(sAMAccountName=$($_.sAMAccountName))"
  $account = $searcher.FindOne()
  if ( $account ) {
    $exists = $true
    $disabled = ($account.Properties["useraccountcontrol"][0] -band $ADS_UF_ACCOUNTDISABLE) -ne 0
  }
  else {
    $exists = $false
    $disabled = "N/A"
  }
  [PSCustomObject] @{
    "sAMAccountName"  = $_.sAMAccountName
    "AccountExists"   = $exists
    "AccountDisabled" = $disabled
  }
}

Upvotes: 2

Related Questions