简体   繁体   中英

Powershell Get-ADuser and Import-CSV

I am trying to Import a CSV file that has the following fields:

Ticket      User
1234657     ABC1234
2456875     ABC9876

Where User = SamAccountName

I have the following code:

 $File = Import-CSV C:\\file.csv
 $File | ForEach  { Get-ADUser -Identity ($_.User) -Properties * | Select-Object SamAccountName, DisplayName, @{Name=’Ticket';Expression={$_.ticket}}}

The output looks like the following:

SamAccountName       DisplayName          Ticket
--------------       -----------          ------
ABC1234              John, Doe
ABC9876              Jane, Doe

So something is happening where the ticket isn't populating in the output table... I want it to look like the following:

SamAccountName       DisplayName          Ticket
--------------       -----------          ------
ABC1234              John, Doe            1234657
ABC9876              Jane, Doe            2456875

Does anyone know what I am doing wrong with my code?

Also if I do just $_.Ticket instead of the expression statement it makes the individual ticket numbers as my header... Example:

SamAccountName  : ABC1234
DisplayName     : John, Doe
Description     : New Account
enabled         : True
1234657         : {}

SamAccountName  : ABC9876
DisplayName     : Jane, Doe
Description     : New Account
enabled         : True
2456875         : {}

$_ is the output from Get-ADUser when you reach Select-Object . You need to save the ticket at the start of the foreach-loop. Try:

$File = Import-CSV C:\\file.csv
 $File | ForEach  {
    #Save ticket
    $ticket = $_.ticket

    Get-ADUser -Identity ($_.User) -Properties * |
    Select-Object SamAccountName, DisplayName, @{Name='Ticket';Expression={$ticket}}
}

When you pipe the results of Get-ADUser to Select-Object, that is what is in $_. Not your original CSV. Here is one solution:

 $File | ForEach  {$t = $_.Ticket; Get-ADUser -Identity ($_.User) -Properties * | Select-Object SamAccountName, DisplayName, @{Name=’Ticket';Expression={$t}}}

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