0

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

1
  • 2
    see get-help *-csv* Commented Oct 23, 2018 at 22:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I had a Add-Content -Path $outputCSVPath -Value '"Name", "SAM Name"' before the foreach loop from a previous attempt. After I got rid of this the "just replace" suggestion worked, but for your loop suggestion I get a .csv with one column named Length and a value of 22970 (which writing to .txt resulted in 51 lines so I'm not sure what that number relates to). Gave you the checkmark anyways for the first solution although would be nice to understand the loop method better
The first suggestion works and appends, since powershell can get finicky and i don't have a setup to test it right now, i'll just remove my second suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.