我在一个文件中有这个内容:
I have this content in a file:
File Versions ---- -------- aaa {1.0.0.123, 1.0.0.124} bbb {1.0.0.123, 1.0.0.124}如何在 powershell 中将其读入表格或类型数组?
我已经通过这个脚本创建了文件:
I've created the file by this script:
$versions = $dictionary | ForEach-Object{ $properties = @{ File = $dictionary.Key Versions = $dictionary.Value <# an array of strings #> } New-Object PSObject -Property $properties } $versions | Out-File "filesVersions.txt"不再使用该脚本.这只是为了演示 filesVersions.txt 文件中的内容.
The script is not used anymore. It's just for demostration of what is in the filesVersions.txt file.
我真正想要的是将一个键值对存储在一个文件中,其中键是文件名,值是版本列表.
What I actually want is to store a key value pairs in a file, where key is FileName and Value is list of versions.
有时我需要读取文件内容,所有新行或新版本到现有行并将其保存回来.
From time to time I need to read the file content, all a new row or a new version to existing row and save it back.
我想为它使用 Format-Table 输出.
I wanted to use Format-Table output for it.
推荐答案我想为它使用 Format-Table 输出. 抱歉,这不是你应该做的方式.你增加了很多不必要的开销.您正在查看可能不可靠和乏味的字符串解析.
I wanted to use Format-Table output for it. Sorry but that is not the way you should be doing it. You are adding a lot of unnecessary overhead. You are looking at string parsing which can be unreliable and tedious.
PowerShell 的力量来自对象.在这种情况下,使用 Export-CSV 将是理想的选择.但是,您需要对该数组进行双向处理.
PowerShell's power comes from objects. Using Export-CSV would be ideal in this situation. However you would need to do something with that array going both directions.
$versions = $dictionary | ForEach-Object{ $properties = @{ File = $dictionary.Key Versions = $dictionary.Value -join "|" } New-Object PSObject -Property $properties } $versions | Export-Csv "filesVersions.csv" -NoTypeInformation当您将数据重新导入 PowerShell 以获取对象时,您需要拆分该字段以获取数组.
When you go to import the data back into PowerShell to get the objects you would need to split that field to get the array back.
Import-Csv "filesVersions.csv" | ForEach-Object{ # Update the property $_.Versions = $_.Versions -split "|" # Send the updated object down the pipe $_ }或者使用计算属性
Import-Csv "filesVersions.csv" | Select-Object File,@{Name="Versions";Expression={$_.Versions -split "|"}}就像马蒂亚斯说的,您也可以使用Export-CLIXML 并且您不需要执行连接或任何操作.我个人认为这是为了更复杂的输出然后你在这里做什么.
Like Mathias says you could also use Export-CLIXML and you would not need to do the join or anything. I personally think that is for more complex output then what you are doing here.
更多推荐
如何从文件中读取powershell表
发布评论