首页 > 解决方案 > PowerShell - 重组代码以从组中删除,然后在进入下一个组之前添加到组

问题描述

你将不得不原谅我,因为我在这里明显超出了我的能力范围。

我有 2 个列表,都包含一个组,然后是技能。第一个列表是需要从组中删除的技能,第二个列表是必须重新添加的列表。

团体 技能
第 1 组 技能1
第 1 组 技能2
第 2 组 技能1
第 2 组 技能2
... ...
第 15 组 技能7

我可以通过拉入列表(其为 CSV 格式)并从组中删除所有技能,然后重新添加它们来做到这一点。

foreach ($groups in $Profiles2Cleanse) {
<command called that actually performs this on a platform but removed for privacy>
Write-Output "$(Get-Date) - Removing - $($groups.Group) - $($groups.Skill)" #just for debug
}
foreach ($groups in $KnownGoodProfileList) {
<command called that actually performs this on a platform but removed for privacy>
Write-Output "$(Get-Date) - Adding - $($groups.Group) - to - $($groups.Skill)" #just for debug
}

我想要做的是遍历每个组并删除所有技能,然后添加它们 - 这就是我卡住的地方。所以类似于:

Remove all skills from Group 1 on Profiles2Cleanse list
Add all skill from Group 1 on KnownGoodProfileList
Remove all skills from Group 2 on Profiles2Cleanse list
Add all skill from Group 2 on KnownGoodProfileList
....
Remove all skills from Group 15 on Profiles2Cleanse list
Add all skill from Group 15 on KnownGoodProfileList

任何帮助将不胜感激。

标签: powershell

解决方案


您应该能够使用Compare-Object来查找列表之间的差异和相等性。

# The main list that is being updated
$master = Import-Csv master.csv

# Groups and Skills combinations that need to be removed from master.csv
$remove = Import-Csv remove.csv

# Groups and Skills combinations that need to be added to master.csv
$add = Import-Csv add.csv

# Remove unwanted groups/skills
# Finds only unique items from master list when compared to removed list
$master = Compare-Object -ReferenceObject $master -DifferenceObject $remove -Property Group,Skill |
    where SideIndicator -eq '<=' |
        Select Group,Skill

# Add new groups/skills
# Finds all items from master and add lists (no duplicates)
$master = Compare-Object -ReferenceObject $master -DifferenceObject $add -Property Group,Skill -IncludeEqual |
    Select Group,Skill

# Update master.csv
$master | Export-Csv master.csv -NoTypeInformation

推荐阅读