2

I am using PowerShell to read and loop through a CSV file in order to create a new file for each row of the CSV file. I need to use the header names as part of each new file.

For each row of the CSV, how can I loop through each column and output the key and value for each variable in the output of each new file?

For example, if Master.csv contains

a,b,c
1,2,3
4,5,6

I would like to output a file named file1.txt:

a=1
b=2
c=3

and a file named file2.txt:

a=4
b=5
c=6

Is there an advantage to converting the array into a hash table, and using something like $d.Keys?

I am trying the below, but cannot get the key:

Import-Csv "C:\Master.csv" | %{
    $CsvObject = $_
    Write-Output "Working with $($CsvObject.a)"
    $CsvObject | ForEach-Object { 
        Write-Output "Key = Value`n" 
    }
}

1 Answer 1

4

this will do the job, it seems. [grin] it uses the hidden .PSObject property to iterate thru the properties of each object.

# fake reading in a CSV file
#    in real life, use Import-CSV
$Instuff = @'
a,b,c
1,2,3
4,5,6
'@ | ConvertFrom-Csv

$Counter = 1

foreach ($IS_Item in $Instuff)
    {
    $FileName = "$env:TEMP\HamletHub_File$Counter.txt"
    $TextLines = foreach ($Prop in $IS_Item.PSObject.Properties.Name)
        {
        '{0} = {1}' -f $Prop, $IS_Item.$Prop
        }

    Set-Content -LiteralPath $FileName -Value $TextLines

    $Counter ++
    }

HamletHub_File1.txt content ...

a = 1
b = 2
c = 3
Sign up to request clarification or add additional context in comments.

6 Comments

Depending on the size of the data set using Add-Content per iteration over the keys might reduce memory usage.
@hsimah - wouldn't that make for MORE writes? writes are SLOW compared to the rest of the script ...
It would make for more writes and it would slow it down. But if you are processing millions of rows in a massive CSV it might be necessary to make the tradeoff of speed.
@hsimah - ah! that would make sense ... thank you for clarifying that! [grin]
Thanks, it is not a huge file, I will test the above
|

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.