Reputation: 51
Please I need help to do this in PowerShell using array. I have an array similar to $a below:
$a = @('**ABC**:XYZ','**LMN**:PQR','**ABC**:RST','YJQ:PRS','**LMN**:SDK')
I want to change the $a
array to $b
:
$b = @('**ABC**:XYZ,RST','**LMN**:PQR,SDK','YJQ:PRS')
The idea is that all items that have common values before ":" should be combined in the format like "common_value:x,y,z" but others without common values should be left alone. Any hint or solution will be appreciated.
Upvotes: 3
Views: 115
Reputation: 7087
A quick and dirty example:
$a = @('**ABC**:XYZ','**LMN**:PQR','**ABC**:RST','YJQ:PRS','**LMN**:SDK')
$b=
$a |
Select-ObJect @{Name = 'Name'; Expression = { $_.Split(':')[0] }},
@{Name = 'Group'; Expression = { $_.Split(':')[1] }} |
Group-Object -Property Name |
ForEach-Object{ "'$($_.Name):$($_.Group.Group -join ',')'"}
$b = $b -join ','
$b
Output:
'**ABC**:XYZ,RST','**LMN**:PQR,SDK','YJQ:PRS'
This also works:
$a = @('**ABC**:XYZ','**LMN**:PQR','**ABC**:RST','YJQ:PRS','**LMN**:SDK')
$b =
$a | Group-Object {$_.Split(':')[0]} |
ForEach-Object{
"'$($_.Name):$(($_.Group.Split(':') | Group-Object { $Global:i % 2; $Global:i++ })[1].Group -join ',')'"
}
$b = $b -join ','
$b
Upvotes: 1
Reputation: 27786
$b = $a | ConvertFrom-String -Delimiter ':' |
Group-Object P1 |
ForEach-Object { "$($_.name):$($_.group.P2 -join ',')" }
ConvertFrom-String
splits each input string at ':', creating an object with properties P1
and P2
for part before and after ':'Group-Object
groups by part before ':'ForEach-Object
we build the result string from part before ':' with part(s) after ':'Upvotes: 1