Powershell。从txt文件和表单列表中选择值

Powershell。从txt文件和表单列表中选择值,powershell,Powershell,我有一个包含如下数据的txt文件: PC:DELL:2018 PC:HP:2016 PC:HP:2016 PC:DELL:2020 要将其解析为: PC:DELL:2018,2020 PC:HP:2016 如果有多对制造商,则需要删除重复行并为每个唯一制造商(HP、DELL)追加年份:年份 谢谢 更新 在此之前给出的建议: Start by parsing each line and create corresponding objects with two properties

我有一个包含如下数据的txt文件:

 PC:DELL:2018
 PC:HP:2016
 PC:HP:2016
 PC:DELL:2020
要将其解析为:

 PC:DELL:2018,2020
 PC:HP:2016
如果有多对制造商,则需要删除重复行并为每个唯一制造商(HP、DELL)追加年份:年份

谢谢

更新

在此之前给出的建议:

Start by parsing each line and create corresponding objects with two properties each:

$objects = Get-Content .\path\to\file.txt |ForEach-Object {
  $parts = $_.Split(':')
  [pscustomobject]@{
    Manufacturer = $parts[0]
    Model = $parts[1]
  }
}

Now you can use Group-Object to group the objects by common Manufacturer:

$groups = $objects |Group-Object Manufacturer

And finally we can construct the desired output string based on the resulting groups:

$groups |ForEach-Object {
  # Extract the model numbers from the objects in each group, join into a single string 
  $models = $_.Group.Model -join ', '
  # Concatenate with the manufacturers name
  '{0}:{1}' -f $_.Name,$models
}
它起作用了。在一开始(为了简化),我要求在每行中有两个“单词”的任务,并从成员那里得到了解决方案(感谢Mathias R.Jessen)。但实际上不止两个


如果有三个或更多的单词,我不知道是否可以使用“Group Object”的解决方案。但这个想法很好。

是的,类似的解决方案在这里也适用

例如:

$values = Import-Csv -Path .\path\to\file.txt -Delimiter ':' -Header 'Type', 'Manufacturer', 'Year'

$groups = $values | Group-Object -Property 'Type','Manufacturer'

$groups | ForEach-Object {
    $typeMfg = $_.Name -replace ', ', ':'
    $years = ($_.Group.Year | Sort-Object -Unique) -join ','
    "{0}:{1}" -f $typeMfg, $years
}