Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regroup common items values in the same array using Powershell

Tags:

powershell

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.

like image 354
Mankensin Avatar asked Aug 12 '26 05:08

Mankensin


1 Answers

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
like image 183
Steven Avatar answered Aug 13 '26 22:08

Steven