Search code examples
powershellhashtable

How can I use an array key in a powershell loop?


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" 
    }
}

Solution

  • 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