Tommy K
Tommy K

Reputation: 1807

Outputting a 2 column csv file using Powershell

I have 2 .csv files I'm comparing and I'm saving the results in a text file using

Foreach(..data in dataSet..) {
    #Setting variables

  if("$samInitials" -eq "$ambInitials") {

    "$firstName $lastName`t$samName`n" | Add-Content $outputFile

    #$account = New-Object psobject -Property @{'Name'="$firstName $lastName"; 'SamName'="$samName"}
  }
  #$outputFile += $account
}
#$outputFile | Export-Csv $outputCSVPath -NoTypeInformation
#commented out lines are the attempt to write to .csv file

How can I make (create a new if file doesn't exist) this append to a 2 column .csv file where column 1 is the first & last name and column 2 is the samName? If its easier I can manually create the .csv and name the columns myself but I have no idea how to go about doing this.

I'm literally brand new to Powershell so sorry if this is obvious but I've been working on this for the past 5 hours (aka since I've learned Powershell) and just need some help with this last step

Upvotes: 0

Views: 4771

Answers (1)

Robert Cotterman
Robert Cotterman

Reputation: 2268

just replace

"$firstName $lastName\: $samName `n" | Add-Content $outputFile

with

New-Object psobject -Property @{'Name'="$firstName $lastName";
                                                             'SamName'=$samName} | 
    export-csv c:\output.csv -append -notypeinformation

This creates a custom object, which powershell can then directly convert to csv

Also don't feel bad, this isn't obvious.

Upvotes: 2

Related Questions