Home > Back-end >  Powershell reorder an array using prefixes as headers
Powershell reorder an array using prefixes as headers

Time:11-23

I have the following simple array in a PowerShell variable

Index : 1
Name : Windows 10 Education
Index : 2
Name : Windows 10 Education N
Index : 3
Name : Windows 10 Enterprise
Index : 4
Name : Windows 10 Enterprise N
Index : 5
Name : Windows 10 Pro
Index : 6
Name : Windows 10 Pro N
Index : 7
Name : Windows 10 Pro Education
Index : 8
Name : Windows 10 Pro Education N
Index : 9
Name : Windows 10 Pro for Workstations
Index : 10
Name : Windows 10 Pro N for Workstations

... and I am wanting to reorder it in the example below

Index Name
----- ----
1       Windows 10 Education
2       Windows 10 Education N
3       Windows 10 Enterprise
4       Windows 10 Enterprise N
5       Windows 10 Pro
6       Windows 10 Pro N
7       Windows 10 Pro Education
8       Windows 10 Pro Education N
9       Windows 10 Pro for Workstations
10      Windows 10 Pro N for Workstations

I have tried using split-string with no luck and I am not sure how to proceed.
Any help would be appreciated

CodePudding user response:

Given that you have an array of strings and not an object it would require some parsing to convert it to a [pscustomobject].

There are many ways of parsing the array, here I'm is using ConvertFrom-StringData however the same could be accomplished by the use of split and trim.

Note that, $imageInfo is there just to test the code, in your case you should use the variable containing the results from dism.

$imageInfo = @'
Index : 1
Name : Windows 10 Education
Index : 2
Name : Windows 10 Education N
Index : 3
Name : Windows 10 Enterprise
Index : 4
Name : Windows 10 Enterprise N
Index : 5
Name : Windows 10 Pro
Index : 6
Name : Windows 10 Pro N
Index : 7
Name : Windows 10 Pro Education
Index : 8
Name : Windows 10 Pro Education N
Index : 9
Name : Windows 10 Pro for Workstations
Index : 10
Name : Windows 10 Pro N for Workstations
'@ -split '\r?\n'

for($i = 0; $i -lt $imageInfo.Count; $i  = 2)
{
    [pscustomobject]$(
        $imageInfo[$i].Replace(':','='),
        $imageInfo[$i 1].Replace(':','=') |
        Out-String |
        ConvertFrom-StringData
    )
}

Result

Index Name
----- ----
1     Windows 10 Education
2     Windows 10 Education N
3     Windows 10 Enterprise
4     Windows 10 Enterprise N
5     Windows 10 Pro
6     Windows 10 Pro N
7     Windows 10 Pro Education
8     Windows 10 Pro Education N
9     Windows 10 Pro for Workstations
10    Windows 10 Pro N for Workstations
  • Related