Get sAMAccount from AD with powershell

Viewed 26

I have a CSV file that contains DisplayNames. I am able to read the CSV file, populate the sAMAccount and e-mail address, and save it to another CSV file with the code below.

I now want to add two additional function to this: 1- append the file and add this info to the rows next to each name,
2 - where a user is not found on AD, populate 'Not found' for sAMAccount and e-mail.

$usernames = Import-Csv  "filepath.csv" | ForEach-Object {
Get-ADUser -Filter "name -like '$($_.name)'" -Properties name| 
Select-Object SamAccountName, userPrincipalName} | Export-Csv -Path filepath.csv

Example of csv

name
john block
Helen auntie
joe uncle

What export file looks like

"SamAccountName","userPrincipalName"
"johnb01","john.block@mail.com"
"joeu01","joe.uncle@mail.com"

what I want the file to look

"name", "SamAccountName", "userPrincipalName"
"john block", "johnb01", "john.block@mail.com"
"Helen auntie", "not found", "not found""
"joe uncle", "joeu01","joe.uncle@mail.com"

1 Answers

You would need to add in something to evaluate if you got a user account from AD, and if not to output something in it's place.

Import-Csv  "filepath.csv" | ForEach-Object {
    $User = Get-ADUser -Filter "Name -like '$($_.Name)'" -Properties DisplayName | Select-Object DisplayName,SamAccountName,userPrincipalName
    If($User -ne $null){$User}else{[PSCustomObject]@{displayName=$_;samAccountName='Not Found';userPrincipalName='Not Found'}}
} | Export-Csv -Path filepath.csv
Related