3
votes

I have a list of users in a CSV, but I need to collect the SamAccount attribute from each user by name in the ad.

CSV model

enter image description here

Script

Get-ADObject -Filter 'ObjectClass -eq "user" -and userAccountControl -eq "512"' -Properties * | Select-Object SamAccountName,CN,DisplayName, | Export-CSV -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation

I'm a little lost I don't know how to do a foreach using name

I am trying but without success.

Trying to get samaccountname based on Name on csv file.

Import-Csv -Path C:\Temp\userteste.csv | foreach-Object {Get-ADUser -Filter {Name -like $_.name} -Properties Name | Select-Object samAccountName}

and export to csv file.

1

1 Answers

5
votes

Why use Get-ADObject and not Get-ADUser for this? The latter gives you more of the desired properties you need in the CSV.

As aside, it is wasteful to do -Properties * if all you want is a small set of user attributes.

Something like this should work:

Get-ADUser -Filter "Enabled -eq $true" -Properties DisplayName, CN | 
    Select-Object SamAccountName, CN, DisplayName | 
    Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation

As per your comment you need to get some extra attributes of the users listed in the CSV, you can do this:

Import-Csv -Path C:\Temp\userteste.csv | ForEach-Object {
    Get-ADUser -Filter "Name -like '$($_.Name)'" -Properties DisplayName, CN | 
    Select-Object SamAccountName, CN, DisplayName
} | Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation

Hope that helps