Import from CSV to Hashtable, then export back to CSV

依然范特西╮ 提交于 2019-12-25 03:37:23

问题


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.

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

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.


回答1:


  • To convert the CSV import to a hashtable, you use Group-Object.
  • To export the hashtable back to CSV, you have to use the .GetEnumerator() method to break it down back into objects for use with Export-Csv.

Using the example above:

$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.



来源:https://stackoverflow.com/questions/34864645/import-from-csv-to-hashtable-then-export-back-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!