简体   繁体   中英

Return job titles from Get-ADUser that match csv

I want to import job titles from a csv file into Powershell then use the Get-ADUser to return all active users with those titles and then export to a new csv

Can someone please help?

$csvjobtitle = Import-Csv -Header csvTitle -Path c:\Job_titles.csv

Get-ADUser -Filter {enabled -eq "true" -and Title -eq "$csvjobtitle"} -
Properties SamAccountName, GivenName, Surname, EmailAddress, Title | select 
SamAccountName, GivenName, Surname, EmailAddress, Title | Export-CSV "C:\Ad 
Extract.csv"

Here's one possible solution:

$csvjobtitle = (Import-Csv -Header csvTitle -Path c:\Job_titles.csv).'csvTitle'

$csvjobtitle | ForEach-Object {
    Get-ADUser -Filter {enabled -eq "true" -and Title -eq "$_"} -Properties SamAccountName, GivenName, Surname, EmailAddress, Title | Select SamAccountName, GivenName, Surname, EmailAddress, Title
} | Export-CSV "C:\Ad Extract.csv"

There are two changes to your previous code:

  1. We get back just the 'csvTitle' values from the CSV, rather than an object which has a csvTitle property.
  2. We loop through those values with a ForEach-Object loop which gets the AD user for each title (where the current title is represented via $_ ).

Because ForEach-Object supports the pipeline (and our Get-ADUser cmdlet returns its result to the pipeline), we can simply pipe the results of the ForEach-Object to Export-CSV .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM