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?

1 Answer 1

6

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.

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

Comments

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.