Hey
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?
thanks