从CSV导入Hashtable,然后导出回CSV

Rob*_*ere 0 csv import powershell export hashtable

我有一个CSV,它使用运行日志来更新许多自动化任务的状态.我需要一种快速方法从CSV中查找信息,以便我可以修改它并将其导出回CSV.

对于这个例子,我们假设我正在跟踪正在运行的进程,并且我想使用"ID"属性作为哈希表的键.

$pathCsv = 'C:\test\test.csv'
Get-Process | Export-Csv $pathCsv
Run Code Online (Sandbox Code Playgroud)

我可以很好地从CSV导入,但我不知道如何将其转换为哈希表或从哈希表获取到CSV.

Rob*_*ere 5

  • 要将CSV导入转换为哈希表,请使用Group-Object.
  • 要将哈希表导出回CSV,必须使用.GetEnumerator()方法将其分解为用于Export-Csv的对象.

使用上面的例子:

$pathCsv = ($env:TEMP + '\test.csv')
Get-Process | Export-Csv $pathCsv

#import CSV to array as hash table using the ID property as the key
$toHashTable = Import-Csv $pathCsv | Group-Object -AsHashTable -Property ID

#make changes to hashtable here

#break the hashtable into the pipeline, then grab each $_.Value property
#and break that out of the hashtable into the pipeline
$toHashTable.GetEnumerator() | ForEach{($_.Value).GetEnumerator()} | Export-Csv $pathCsv
Run Code Online (Sandbox Code Playgroud)

我在这里问了这个问题,所以我可以回答其他正在寻找解决同一问题的人.