Home > Mobile >  Powershell - How to Transpose an array
Powershell - How to Transpose an array

Time:12-01

I have an array with data separated by a comma. I need to transpose it so the first part before the comma for each line is joined together by a delimiter as one line and the same for a second part. Example:

AC-2.22,CCI-000012
AC-5.1,CCI-000036
AC-5.3,CCI-001380

I want to have 2 separate variables like so:

variable 1 = AC-2.22; AC-5.1; AC-5.3
Variable 2 = CCI-000012; CCI-000036; CCI-001380

I know this should be simple but I've been staring at code all day and I just want to go eat dinner and goto sleep.

Thanks in advance

CodePudding user response:

This is not too hard using .Where method with Split mode:

$array = @(
    'AC-2.22,CCI-000012'
    'AC-5.1,CCI-000036'
    'AC-5.3,CCI-001380'
)

$i = $false
$var1, $var2 = $array.Split(',').Where({ ($i = -not $i) }, 'Split')
$var1 -join '; '
$var2 -join '; '

.Split method works in this case thanks to Member-Access Enumeration, because arrays don't have an .Split method the same is called over each element of the array:

When you use the member-access operator on any object and the specified member exists on that object, the member is invoked. For property members, the operator returns the value of that property. For method members, the operator calls that method on the object.

When you use the member-access operator on a list collection object that doesn't have the specified member, PowerShell automatically enumerates the items in that collection and uses the member-access operator on each enumerated item.

CodePudding user response:

Based on the $array of the helpful answer from Santiago Squarzon, you might also use the ConvertFrom-Csv cmdlet to transpose the data using member-access enumeration:

$data = ConvertFrom-Csv $Array -Header var1, var2
$data.var1 -Join ';'
AC-2.22;AC-5.1;AC-5.3
$data.var2 -Join ';'
CCI-000012;CCI-000036;CCI-001380
  • Related