Importing extra column from CSV and exporting it to a CSV

Hello Everyone,

I am Importing a CSV (test.csv)with usernames in 1 column and other Information in other column and pulling Information from AD based on those usernames, which I can export to a CSV no problem, but I also want to keep another column from(test.csv) as it is and want to export it to my (result.csv) and I am unable to do that. Here is my code.

$testcsv = Import-csv -path “C:\Users\username\Documents\Script\TestFolder\test.csv”

ForEach($user in $testcsv)
$usercsv = $user.user

get-aduser -filter {samaccountname -eq $usercsv} -properties * |
select-object NAME,whencreated,whenchanged ,@{Name=“Time Difference” ;Expression = {(New-TimeSpan -Start $.whencreated -end $.whenchanged).TotalDays}}, `
@{Name=“AnotherColumn” ; Expression = {$testcsv | Select-Object -property other}}


You can covert your CSV file input into PowerShell Customer Object first where you can take all the headers from csv which you need and then add the logic for pulling Information from AD.


If I understand correctly, you want to export (3) columns per user from test.csv, add AD info then export the results. Below should work for you.
I put the results of the loop in a variable then exported the variable contents to csv.

No need for username in variable or to list all AD properties

$testcsv = Import-csv -path "C:\Users\username\Documents\Script\TestFolder\test.csv"

$result =
ForEach($user in $testcsv) {
  Get-Aduser -filter {samaccountname -eq $user.user} -properties whencreated,whenchanged |
  Select-Object @{Name='User';exp={$user.user}},NAME,whencreated,whenchanged,
  @{Name="Time Difference" ;Expression = {(New-TimeSpan -Start $_.whencreated -end $_.whenchanged).TotalDays}}, `
  @{Name="AnotherColumn" ; Expression = {$user.other}}

$result | Export-Csv -NoTypeInformation -Path .\testresult.csv

Thank You