Powershell - Output string to CSV and format

2019-09-04 03:45发布

问题:

I've given a simple example below. Does anyone know what I have to do to output the string into two columns. My searching has not returned much in the way of formatting outputs into CSV. Please point me in the right direction! Thanks!!!

$LogFile = c:\somefile.csv
"Hello World" | Out-File $LogFile

回答1:

Reading your comments which supplement your question, creating a PSObject around the variables you are trying to export to CSV might give you more control over your output. Consider the following:

$A = "Hello";
$B = "World";

$wrapper = New-Object PSObject -Property @{ FirstColumn = $A; SecondColumn = $B }
Export-Csv -InputObject $wrapper -Path C:\temp\myoutput.txt -NoTypeInformation

Creates the file C:\temp\myoutput.txt with two columns (FirstColumn and SecondColumn) and the variables $A and $B placed in those columns in the first row



回答2:

To be honest with you I think your example is probably too trivial. For the example that you have though:

'Hello World'.Replace(' ',',') | Out-File $LogFile

This will of course give a faulty result if there are spaces that you want to keep in the data. Hence my expectation that your example is too trivial.