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.
ExcelAsked:
Who is Participating?
 
footechCommented:
To both output data on screen and save to a file, you need to perform both actions for each object.  It's a little simpler if you just have string objects, as you could use Tee-Object appending to a file.  Another way is to save all output data into a variable, and at the very end have two commands - one to send data to Format-Table, and one to send data to Export-CSV.

The way I've shown below makes the best use of the pipeline.
Import-csv .\list.csv | Select -ExpandProperty name | ForEach `
{
    $user = $_
    try {
        Get-ADUser $user -Properties DisplayName,LastLogonDate | 
         Select name,displayname,enabled,lastlogondate 
        Write-Host "$user exists" -ForegroundColor Green
    }
    catch {
        Write-Host "$user doesn't exist" -ForegroundColor Yellow
        $user | Select @{n="name";e={$_}},displayname,enabled,lastlogondate
    }
} | Tee-Object -Variable out | Format-Table
$out | Export-Csv -Path output.csv -NoTypeInformation

Open in new window

1
 
MaheshArchitectCommented:
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

0
 
ExcelAuthor Commented:
Hi guys, sorry was away and just reviewing now. Shall post an update shortly if and what options works.
0
 
ExcelAuthor Commented:
Thanks footech, this is exactly what i was after.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.