0

I want to do the following:

$content = $source | ConvertFrom-Csv -Header $HEADER

My problem is the Variable $HEADER. I use Get-Content to get the desired content. Unfortunately this adds quotes around the object, therefore -Header treats the list of columns as one column and ignores the commas.

If I echo $HEADER I get the following: "a","b","c"

But it is treated as: '"a","b","c"'

If I override $HEADER like this everything works: $HEADER = "a","b","c"

Unfortunately I need to use Get-Content because my Header needs to be variable.

I believe -remove "'", "" only deletes characters in the string and not the surrounding quotes.

Any help is much appreciated :)

Katy
  • 13
  • 2

2 Answers2

0
$header = '"a","b","c"';
$header = $header.Split(',');

$HEADER = "a","b","c" is an array, while '"a","b","c"' is a String.

So you should split it to get your desired output.

Dumbi
  • 16
  • 2
0

Get-Content (without switch -Raw) reads a text file as array of lines, so yes, then the header (and all remaining data) is not separated into fields.

Import-Csv will read and parse the input into objects with property names from the existing header or the headers you give it as string array using parameter -Header.

Export-Csv will always quote everything, be it a header or data field, unless you are using PowerShell version 7 and add -UseQuotes AsNeeded to the cmdlet.

Simply trying to remove all quotes in a CSV file is risking mis-alignment in the field order and rendering the csv as unusable. There is a safe way of doing this, see my function ConvertTo-CsvNoQuotes

Theo
  • 57,719
  • 8
  • 24
  • 41