How construct a variable that works with export-csv?

Copper Contributor


I have a small csv file that I import in Powershell into a variable. Here it is (as I can't seem to upload a file):







After importing it I can examine $myCsvVar in many ways.

For example:



$myCsvVar= Import-Csv -Path C:\temp\csvFile.csv -Delimiter ","




However hard I try, I am not able to create such a variable from within Powershell.

Would anybody here know how to do that? 

The reason is that I have to construct a variable as an object that I then can use with export-csv.

Thank you.


3 Replies
Usually you create an array with all the fields (colums) that you need and export it to a .csv using export-csv with the -NoTypeInformation parameter.

Example export to csv with a list of files in c:\temp

[array]$contents=Get-ChildItem c:\temp
$contents | export-csv -Path c:\temp\x.csv -Delimiter ';' -NoTypeInformation

thank you for looking into this.
When I pull contents from my small csv file into a variable, I have no problem to export it again.
However, as I need to get things from here and there, strings mostly, I figured I would construct a variable just like the one I get after importing my csv file.
But that does not work. As long as I pull objects into a variable it is okay. But constructing a variable and putting strings from different places into it seems impossible.
So far I helped myself by writing into a file, knowing that the data in csv must be homogenous troughout.
It would have been elegant to construct the variable first as an object, give it the noteproperties (members) I need and only do one export-csv in the end.
Good New Year 2022 to you - in any case.



One solution would be to create an array of pscustomobjects like so:


for($i=0; $i -lt 10; $i++){
    $myArr = $myArr + [PSCustomObject]@{AAA = ""; BBB = ""; CCC = "" }


Afterwards I can set any cell of the matrix:




The only problem is that I have more then three keys, all through to ZZZ.

As I don't want to type them all, I wonder whether I can get this done programmatically?

I tried to build a string variable and put it within the curly brackets of the hashtable. But the compiler does not allow for that as it requires a hard coded equal sign.

Anybody have an idea?

Thank you