组合Powershell阵列



我有一个数组,在powershell中$x调用它。

$x | ft -autosize
d     c     b
-     -     -
Apple       true
Apple true   
Banana       
Banana true  
Clark       true
David       true
David true  
Eddy  
Eddy        

我正在尝试组合项目。 在这种情况下,我想要的结果是:

$x | ft -autosize
d     c     b
-     -     -
Apple true  true
Banana true  
Clark       true
David true  true
Eddy  

注意:空白可以表示假,但数组在假时通常为空,在真时为 TRUE。 线条并不总是加倍(如上面的克拉克(

当我找到匹配项(如果有的话(时,我可以遍历数组并逐一收集每个元素,但只是继续认为必须有更好的方法。

Group-Object确实是要使用的正确 cmdlet:

# Sample input (constructed from CSV data for convenience)
$x = @'
d,c,b
Apple,,true
Apple,true,
Banana,,  
Banana,true,
Clark,,true,
David,,true
David,true,
Eddy,,
Eddy,,
'@ | ConvertFrom-Csv
$x | Group-Object d | # Group the array of objects by their .d property
ForEach-Object {    # Process each resulting group
# For each .d value, construct a custom object that aggregates
# the .c and .b property values and output it.
[pscustomobject] @{
d = $_.Name # The shared .d value
c = $_.Group.c | Where-Object { $_ } # any non-empty .c values 
b = $_.Group.b | Where-Object { $_ } # any non-empty .b values 
}
}

以上结果:

d      c    b
-      -    -
Apple  true true
Banana true 
Clark       true
David  true true
Eddy        

以下内容应利用Group-Object清理PowerShell中的数组

创建一个名为$exampleArray的数组:

$exampleArray = @()
$names = @("Apple", "Banana", "Clark", "David", "Eddy")
$tOrB = @("True","")
#just for an example
1..20 | % {
$object = New-Object PSObject -Property @{
#Get random Name
d = $names[$(Get-Random -Maximum $names.Count)]
#do true / blank -- random
c = $tOrB[$(Get-Random -Maximum $tOrB.Count)]
b = $tOrB[$(Get-Random -Maximum $tOrB.Count)]
}
$exampleArray += $object
}
$exampleArray

然后我们可以按d分组:

#group "combine" by column d
$group = $exampleArray | Group-Object d

分组后,我们可以遍历分组的名称并构建一个名为$combined的新数组:

$combined = @()
$group | %{
$object = New-Object PSObject -Property @{
d = $_.Name
}    
if($_.Group.c -contains "True")
{
$object | Add-Member -MemberType NoteProperty -Name c -Value "True"
}
else
{
$object | Add-Member -MemberType NoteProperty -Name c -Value ""
}
if($_.Group.b -contains "True")
{
$object | Add-Member -MemberType NoteProperty -Name b -Value "True"
}
else
{
$object | Add-Member -MemberType NoteProperty -Name b -Value ""
}    
$combined += $object
}
$combined

注意:如果您已经加载了数组(在本例中为$exampleArray(,则最好对该数组进行Where-Object...这取决于您尝试完成的确切目标。我提供的答案很可能是矫枉过正

最新更新