从CSV导入到哈希表,然后导出回CSV [英] Import from CSV to Hashtable, then export back to CSV
问题描述
我有一个CSV,它使用运行中的日志来更新许多自动化任务的状态.我需要一种快速的方法来从CSV查找信息,以便可以对其进行修改并将其导出回CSV.
I have a CSV that uses a running log to update the status of a lot of automated tasks. I need a quick method to look up information from the CSV so I can modify it and export it back to the CSV.
在此示例中,假设我一直在跟踪正在运行的进程,并且想将"ID"属性用作哈希表的键.
For this example, let's assume that I'm keeping track of running processes and I want to use the "ID" property as a key for the hashtable.
$pathCsv = 'C:\test\test.csv'
Get-Process | Export-Csv $pathCsv
我可以很好地从CSV导入,但是我不知道如何将其转换为哈希表或将其从哈希表转换为CSV.
I can import from the CSV just fine, but I don't know how to convert it to a hashtable or get it from a hashtable to CSV.
推荐答案
- 要将"CSV导入"转换为哈希表,请使用组对象".
- 要将哈希表导出回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
我在这里问了这个问题,所以我可以为正在寻求解决同一问题的其他任何人回答.
I asked this question here so i could answer it for anyone else who was searching for a resolution to the same problem.
这篇关于从CSV导入到哈希表,然后导出回CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!