Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Using a variable for the fields in Select-Object

Tags:

powershell

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?

like image 565
Patrck R Avatar asked Oct 23 '25 01:10

Patrck R


1 Answers

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.

like image 136
briantist Avatar answered Oct 26 '25 04:10

briantist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!