Too many if statements, how to simplify


I have a CSV with certain accounts that need to be disabled. The CSV includes logon names and employee IDs. These accounts are located in specific OU. My goal is to verify that the accounts obtained from AD match those listed in the CSV before processing them. Below is a snippet of what i’m trying to do.

$today   = (get-date).Date
$csvData = Import-Csv -Path $File.FullName
$ou      = "OU=IT,OU=office 1,DC=abc,DC=dc","OU=Board,OU=office 2,DC=abc,DC=dc"

foreach ($User in $csvData) {
    # Check samaccountname matches the log on name
    # Check employeeid matches employee id 
    # Limit the search to specific OU
    $expiredAccounts =
    foreach ($item in $ou) {
        Get-ADUser -Filter "(SamAccountName -eq '$($user.'Log on Name')') -and (EmployeeID -eq '$($user.'Employee ID')')" -Properties AccountExpirationDate -SearchBase $item -ErrorAction Stop
    # if match is found, check if account has expired
    if (($expiredAccounts) -and ($expiredAccounts.AccountExpirationDate -ne $null) -and ($expiredAccounts.AccountExpirationDate -le $today)) {
        Write-Output $expiredAccounts
    elseif (($expiredAccounts) -and ($expiredAccounts.AccountExpirationDate -eq $null) -or (-not($expiredAccounts.AccountExpirationDate -le $today))) {
        Write-Log "[Warning ] $($User.'Log on name') account is active, no action taken. * $($expiredAccounts.DistinguishedName)" -TimeStamp

    # If no account is found, search AD to see if account exists elsewhere
    elseif ((-not($expiredAccounts))) {
        $checkDisabled = Get-ADUser -Filter "SamAccountName -eq '$($user.'Log on Name')'"     
        # Is the account already disabled and in disabled OU? log it 
        if (-not($checkDisabled.Enabled) -and ($checkDisabled.DistinguishedName -match 'OU=disabled')) {
            Write-Log "$($User.'Log on name') is already disabled, no action taken" -TimeStamp
        else {
            Write-Log "[Warning ] $($User.'Log on name') Account not processed, either account is not in the specified OU or employeeid and log on name did not match AD . * $($checkDisabled.DistinguishedName)" -TimeStamp

It does work but i think too many if statements and i’m wondering if there is a better approach?


If that’s your only requirement I wonder why you have to check more than the sAMAccountName. Since the sAMAccountName is unique in an AD you don’t need to check anything else if you have this bit of information on both sides of your comparison. :man_shrugging:t3:

And BTW: If you want to compare objects you can use Compare-Object. You just have to make sure that both arrays have one common property name you can compare on. :wink:

1 Like

i wanted to match both fields and didn’t want to process those that are missing employee id. But yes, i should remove it.

thanks, will try that approach and post back later

I don’t know where you get the CSV data from and of what quality they are but maybe you should define your actual requirement more clearly and focus on that only. :wink:

thanks, ok will do.

I had a go at using compared-object. looked at some examples i’ve seen yourself and krzydoug use in this forum.

$today  = (get-date).Date
$csv    = Import-Csv $newPath.FullName | Select-Object -Property *,@{Name = 'samaccountname'; Expression = {$_.'Log on Name'}} 
$ou     = "OU=IT,OU=office 1,DC=abc,DC=dc","OU=Board,OU=office 2,DC=abc,DC=dc"

$expiredusers =
foreach ($item in $ou) {
    Get-ADUser -Filter * -Properties Memberof,
    Title,AccountExpirationDate,Manager,EmployeeID -SearchBase $item | 
    Where-Object {Compare-Object -ReferenceObject $_.samaccountname -DifferenceObject $csv.samaccountname -IncludeEqual -ExcludeDifferent}

just need to workout how to log if no match is found etc but i’ll check if that is required.

I’m afraid you misunderstood how Compare-Object works or how it is usually used … it’s supposed to compare more than one object at a time.

$csvList = Import-Csv $newPath.FullName | Select-Object -Property *, @{Name = 'samaccountname'; Expression = { $_.'Log on Name' } } 
$ouList = "OU=IT,OU=office 1,DC=abc,DC=dc", "OU=Board,OU=office 2,DC=abc,DC=dc"

$ADUserList = 
foreach ($ou in $ouList) {
    Get-ADUser -Filter * -Properties Memberof, Title, AccountExpirationDate, Manager, EmployeeID -SearchBase $ou 

Compare-Object -ReferenceObject $csvList -DifferenceObject $ADUserList -Property sAMAccountName -IncludeEqual -PassThru
1 Like