[英]Powershell create a new object array based on one, with certain items to be removed
I am trying to create a new array based on some rules I have to follow.我正在尝试根据我必须遵循的一些规则创建一个新数组。 I am sure there is some easier way to do this but I cannot figure it out!
我相信有一些更简单的方法可以做到这一点,但我无法弄清楚!
$files
array contains the following: $files
数组包含以下内容:
Name Amount
----------- --------------
KL 3
KS 55
KS 54
KS 50
KM 4
KD 1
KW 4
KD 3
KV 4
KD 4
KL 7
KS 1
I want to create a new array in the same order as the above, but remove all but the latest KD & KL
name.我想以与上述相同的顺序创建一个新数组,但删除除最新的
KD & KL
名称之外的所有内容。 Which would look like:看起来像:
KS 55
KS 54
KS 50
KM 4
KW 4
KV 4
KD 4
KL 7
KS 1
So far I have been trying to forloop to work out the amount of KD & KL's but I am getting confused with how to just add the ones later in the list.到目前为止,我一直在尝试使用 forloop 来计算 KD 和 KL 的数量,但我对如何在列表的后面添加这些感到困惑。
Use an ordered dictionary to keep track of the last seen object with a given name:使用有序字典来跟踪最后看到的具有给定名称的对象:
$latest = [ordered]@{}
$files |ForEach-Object {
$latest[$_.Name] = $_
}
$arrayWithOnlyLatest = $latest.Values
$arrayWithOnlyLatest
now contains only the last seen objects with each name $arrayWithOnlyLatest
现在只包含每个名字最后看到的对象
I'm sure there is a much more clever way, but instead of getting the last KD/KL, you could just do the opposite.我敢肯定有更聪明的方法,但不是获得最后一个 KD/KL,你可以做相反的事情。 Reverse the array, only keep the first KD/KL, then reverse the array back.
反转数组,只保留第一个KD/KL,然后反转数组。
[array]::Reverse($files)
$kdfound = $klfound = $false
$files = switch -Regex ($files)
{
'KD' {if($kdfound -eq $false){$kdfound = $true; $_}}
'KL' {if($klfound -eq $false){$klfound = $true; $_}}
default {$_}
}
[array]::Reverse($files)
$files
Output输出
Name,Amount
KS,55
KS,54
KS,50
KM,4
KW,4
KV,4
KD,4
KL,7
KS,1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.