petben Posted May 18, 2022 Posted May 18, 2022 Hello, in PowerShell I want to import a csv, e.g.: name, email james, [email protected] mark, [email protected] then from the imported .csv 'email' field I want to get the corresponding AD users can someone please help?
howartp Posted May 18, 2022 Posted May 18, 2022 $csvFile = "n:\csv.csv" $csv = Import-Csv $csvFile foreach ($line in $csv) { $name = $line.name $email = $line.email Get-ADUser -filter 'mail -eq $email' } 1
petben Posted May 18, 2022 Author Posted May 18, 2022 thanks, why do you need the $name = $line.name?
howartp Posted May 18, 2022 Posted May 18, 2022 You don't. I'm assuming you will be developing the code further to "do" something else, so I made it easier to have the name and email in variables ready for using.
DaveTheTech Posted May 18, 2022 Posted May 18, 2022 This will call get-aduser each time. It would be better to get all of your users. Limiting the results where you can, then filter the results against the spreadsheet. Something similar to this: $adUsers = get-aduser -SearchBase "OU=Staff, OU=Users, DC=domain, DC=com" -Filter {enabled -eq $true} $csv = import-csv file.csv $adUsers.where({$_.UserPrincipalName -like $csv.UPN})
howartp Posted May 18, 2022 Posted May 18, 2022 I knew someone would say that I make scripts up as I go along so I'd have been doing $allusers = get-aduser for (line in csv) { for user in $allusers { } } which I wouldn't have been proud of. It depends if he has more $csvlines or more $users.
petben Posted May 18, 2022 Author Posted May 18, 2022 why does this return nothing for $ADUsersfromCSV? $ADUsers = get-aduser -SearchBase "OU=Students,DC=school,DC=com" -Filter {enabled -eq $true} $CSVUsers = Import-Csv 'D:\User_Export.csv' $ADUsersfromCSV = $ADUsers | where {$_.UserPrincipalName -like $CSVUsers.Email}
howartp Posted May 18, 2022 Posted May 18, 2022 Are your UserPrincipalName's actually email addresses? Ours are [email protected]al, not [email protected] Also I presume you've intentionally anonymised the SearchBase to "OU=Students,DC=school,DC=com" - if not, that needs changing to your actual AD path.
petben Posted May 18, 2022 Author Posted May 18, 2022 I changed the AD path yes, $ADUsers: returns lots of users. UserPrincipalName is indeed an email address in the form external domain $CSVUsers: First Last Email ----- ---- ----- Jay Brown [email protected] Mark Aman [email protected] Thanks
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now