Reputation: 3
I have a list of names that I need to work out the AD usernames for, the list is in the same format as the display name in AD.
I ran the following code
Get-Content c:\test\users.txt |
Foreach-Object {Get-ADUser -filter "displayName -like '$($_)'" |
Select-Object SamAccountName,name} |
Export-Csv c:\test\output1.csv
This outputted a list of Usernames and names, however it only outputted successful name resolutions.
What I would like to do is be able to have a list of names to verify against. This could return an error for two reasons:
For example
input.txt
would be a list of names in the format of display name.
Output I would like:
Original Input Exists in AD Username Name 1 True Username1 Name 2 True Username2 etc. False Check
Many Thanks in Advance
Upvotes: 0
Views: 983
Reputation: 1660
You could create a custom object in the pipeline. Also using LDAP filter anr
(Ambiguous Name Resolution) might work better with the list of names, because it looks up multiple properties of users to find matches.
The solution could be something like this:
Get-Content "C:\test\users.txt" |
Foreach-Object {$user=get-aduser -ldapfilter "(anr=$_)"; `
[PSCustomObject]@{Name=$_; Username=$user.samaccountname; Exists=&{$user -ne $null}}} |
Export-Csv "c:\test\output1.csv"
Upvotes: 1
Reputation: 23830
Using this Join-Object
cmdlet from the PowerShell Gallery:
Get-Content .\Users.txt | ForEach {[PSCustomObject]@{Name=$_; InList=$True}} |
FullJoin (Import-Csv .\output1.csv) Name
Will output something like:
Name InList SamAccountName
---- ------ --------------
name1 True Sam1
name2 True
name5 True Sam5
Name3 Sam3
Upvotes: 0
Reputation: 40998
You have to test if something was returned from Get-ADUser
and do something else if you got nothing.
I think this should do what you're looking for, but you might want to tweak it:
Get-Content c:\test\users.txt | Foreach-Object {
$user = Get-ADUser -filter "displayName -like '$($_)'" -Properties DisplayName,SamAccountName,Name
if ($user) {
$user | Select-Object DisplayName,SamAccountName,Name
} else {
$_ | Select-Object @{Label="DisplayName";Expression={"$_"}},@{Label="SamAccountName";Expression={""}},@{Label="Name";Expression={""}}
}
} |export-csv c:\test\output1.csv
If nothing is found, this will output just the display name from the file. All that Label=
and Expression=
notation is to make sure it outputs the same properties that are output when something is found, so the list can be all put together.
Upvotes: 0