4

I'm building a script that is creating csv files. Each csv has a different set of fields. Everything is working great, but I want to control the column order output. I have a variable that contains the fields and the order I want them in.

I know that I can use Select-Object to control this. What I want to do is this:

$Fields = "ID,Field1,Field2,Field3,Field4"
$Obj | Select-Object $Fields | Export-CSV -Path $OutputPath

Instead of this:

$Obj | Select-Object "ID","Field1","Field2","Field3","Field4" | Export-CSV -Path $OutputPath

Since I have several different formats and want to just pass the field list as a parameter to the function doing the work. Is this possible?

briantist
  • 45,546
  • 6
  • 82
  • 127
Patrck R
  • 41
  • 1
  • 3

1 Answers1

5

Yes it is absolutely possible.

When you pass in "ID,"Field1","Field2","Field3","Field4" that is just an array of strings.

To show a literal example:

$Fields = "ID","Field1","Field2","Field3","Field4"
$Obj |Select-object $Fields |export-csv -path $OutputPath

How you assign the value of $Fields during each iteration is up to you.

briantist
  • 45,546
  • 6
  • 82
  • 127