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

  • This topic has 3 replies, 3 voices, and was last updated 7 months ago by
    Participant
    .
Viewing 3 reply threads
  • Author
    Posts
    • #167074
      Participant
      Topics: 6
      Replies: 6
      Points: 68
      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: 45
      Points: 243
      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: 5
      Replies: 290
      Points: 244
      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: 6
      Replies: 6
      Points: 68
      Rank: Member

      Thank You

Viewing 3 reply threads
  • The topic ‘Importing extra column from CSV and exporting it to a CSV’ is closed to new replies.