I have a CSV file I downloaded from my company's Duo Admin Portal of over 4k "Inactive Users".
I am trying to write a PowerShell script that I can export the results as such:
- For users found still in Active Directory = User - Email - Enabled
- For users not found in Active Directory = User " not found."
The closest code that I have come up with is:
$InputFile = C:\Users\name\desktop\TestingSample1.csv
$CheckADUser = Import-CSV $InputFile | ForEachObject {GetADUser -f "samAccountName -eq $($_.)"}
$OutputFile = C:\Users\name\desktop\DuoInactiveUser.csv
$Result =
if ($CheckADUser -ne $null) {
-Properties samAccountName,mail,enabled | select @{name= '$DuoInactiveUsers.Username';expression= {$_.samAccountName}},@{name= '$DuoInactiveUsers.Email';expression={$_.mail}},@{name= 'DuoInactiveUsers.Enabled';expression={$_.Enabled}}}
else {
@{name= 'DuoInactiveUsers.Username';expression="{$_.samAccountName} not found!"
$Result | Export-CSV $OutputFile -Append
The problems I am running into are:
- Not all listed user names in the exported CSV, are in the samAccountName format. Some are in logon name format.
- I keep getting the error "ObjectNotFound: ((name):ADUser) [Get-ADUser], ADIdentityNotFoundException" instead of producing the else statement.
I have tried looking up the error for ways to fix the issue, and found a few options, but none of them appear to be working.
I have tried to catch the error but I do not have the permissions with my work profile to add PowerShell modules that I have found elsewhere that are supposed to work.
Your current code has many syntax errors, leaving that aside, if your CSV values can have
samAccountName
orUserPrincipalName
you can change your filter to target both possibilities. I added some inline comments to help you follow the logic of the code. An important thing to note, it seems like you're trying to have dynamic properties depending on if the user was found or not, this is not possible withExport-Csv
, you must create uniform objects (objects that will have the same structure, same property names) otherwise you will lose data.