Link to home
Start Free TrialLog in
Avatar of Excel
ExcelFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Powershell script with Try and Catch to compare AD users vs CSV list

Powershell script with Try and Catch to compare AD users vs CSV list.

Can't figure out how to get data out on screen and into csv. I'm after data if user exist or not on AD, if account is enabled\disabled and last logon date.  How to write-output of all properties i'm after and format table.

$users = Import-csv .\list.csv | Select -ExpandProperty name

foreach ($user in $users) {
try {
get-aduser $user -Properties * |select enabled,name,displayname,lastlogondate
Write-Output "$user exists "
}

catch {
write-output "$User doesn't exist"
}
}

Your help is much appreciated.
Avatar of Mahesh
Mahesh
Flag of India image

Try below

CSV should have "Name" as header underneath all usernames SamAccountName should be there
What data you have?

$users = Import-csv .\list.csv

 foreach ($user in $users) {

 try {
 $ADUser =  get-aduser -Filter {Name -Like $user.Name} -Properties * -Erroraction SilentlyContinue

if ($ADUser.SamAccountName -ne $null) {

Select SamAccountName, DisplayName, Enabled, Lastlogondate | Export-csv C:\availableusers.txt -NotypeInformation -Append -Force

   }

Else {
"$($user.name) does not exists" | out-file "C:\Unavailableusers.txt" -Append -Force

 }
}

 catch {
 write-output "$User doesn't exist"
 }
 } 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Excel

ASKER

Hi guys, sorry was away and just reviewing now. Shall post an update shortly if and what options works.
Avatar of Excel

ASKER

Thanks footech, this is exactly what i was after.