带有哈希表头的Powershell CSV

Tee*_*Zee 4 csv powershell

我有一个带标题行的csv文件,我想将其转换为Hashtable。

例如,这是我的输入:

#Version1.0
#Fields:ID,Data
1,data1
2,data2
3,data3
Run Code Online (Sandbox Code Playgroud)

我希望输出是其中键= ID和值=数据的哈希表。

这就是我所拥有的,但结果并不完全符合我想要的。

$mytable = Import-Csv -Path $filePath -Header ID,Data
$HashTable=@{}
foreach($r in $mytable)
{
    $HashTable[$r.ID]=$r.Data
}
Run Code Online (Sandbox Code Playgroud)

这将创建我的表,但是当我稍后通过$ str = $ Hashtable |输出时。字符串写主机$ str

我得到以下内容:

Name                  Value
--------              -----------
#Fields:ID            Data
1                     data1
2                     data2
3                     data3
Run Code Online (Sandbox Code Playgroud)

如何摆脱将标头写入哈希表的问题?有没有比坚持if($ r.ID.StartsWith(“#”)){继续;}?

谢谢!-C

小智 6

The default behavior in Import-Csv is to use the first (un-commented) line as the headers. Instead of defining the header in the command, remove "#Fields:" from the header line.

#Version1.0
ID,Data
1,data1
2,data2
3,data3
Run Code Online (Sandbox Code Playgroud)

Then you can create the hashtable like this:

$mytable = Import-Csv -Path $filePath
$HashTable=@{}
foreach($r in $mytable)
{
    $HashTable[$r.ID]=$r.Data
}
Run Code Online (Sandbox Code Playgroud)

Which returns:

Name                           Value
----                           -----
2                              data2
1                              data1
3                              data3
Run Code Online (Sandbox Code Playgroud)


Gre*_*reg 5

$HashTable = @{}
Import-Csv $filePath | % { $HashTable[$_.ID] = $_.Data }
Run Code Online (Sandbox Code Playgroud)


mjo*_*nor 1

不知道它是否“更优雅”,但是:

$mytable = Import-Csv -Path $filePath -Header ID,Data
$HashTable=@{}
foreach($r in $mytable)
{
    if ($r.ID -notlike '#*')
     {$HashTable[$r.ID]=$r.Data}
}
Run Code Online (Sandbox Code Playgroud)