Importing extra column from CSV and exporting it to a CSV

Welcome Forums General PowerShell Q&A Importing extra column from CSV and exporting it to a CSV

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
2 months ago.

  • Author
    Posts
  • #167074

    Participant
    Topics: 5
    Replies: 5
    Points: 54
    Rank: Member

    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}}

    }

  • #167089

    Participant
    Topics: 0
    Replies: 44
    Points: 235
    Helping Hand
    Rank: Participant

    @aman
    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.

    Example: 
    https://stackoverflow.com/questions/48270462/creating-a-custom-powershell-object-from-csv-input?answertab=active#tab-top
  • #167128

    Participant
    Topics: 4
    Replies: 269
    Points: 115
    Helping Hand
    Rank: Participant

    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.

    TIP:
    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
    
  • #167200

    Participant
    Topics: 5
    Replies: 5
    Points: 54
    Rank: Member

    Thank You

You must be logged in to reply to this topic.