如何在 Powershell 循环中使用数组键?

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

我正在使用 PowerShell 读取和循环访问 CSV 文件,以便为 CSV 文件的每一行创建一个新文件。我需要使用 header 名称作为每个新文件的一部分。

对于 CSV 的每一行,我如何遍历每一列并在每个新文件的输出中输出每个变量的键和值?

例如,如果 Master.csv 包含

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

我想输出一个名为 file1.txt:

的文件
a=1
b=2
c=3

和一个名为 file2.txt:

的文件
a=4
b=5
c=6

将数组转换为散列 table 并使用 $d.Keys 之类的东西是否有优势?

我正在尝试以下方法,但无法获取密钥:

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

看来,这样就可以了。 [grin] 它使用隐藏的 .PSObject 属性 来遍历每个对象的属性。

# 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内容...

a = 1
b = 2
c = 3