Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build List of Lists from Delimited String in Powershell

Very Simply put I am looking to take a string that is X length and parse it into an object.

The string will look like this: 0||1||2||3;a||b||c||d;10||11||12||13;

My goal is to pipe that content into the following structure to be used as individual variables and values:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var1 var2 var3 var4
0 1 2 3
a b c d
10 11 12 13

My eventual goal is to be able to loop through these by calling a foreach loop (ie foreach row in table: row.var1 + row.var2 +...etc). The number of rows is not restricted, but the number of variables will always be 4 (I’ll error handle if there are more or fewer).

I can obviously handle the initial part of converting the lines to rows:

$rows = $Content -split ";"

That returns this table:

var
0||1||2||3
a||b||c||d
10||11||12||13

Then I parse through the rows and attempt to make cells (but this doesnt work the way I need it to):

table=@()
foreach ($row in $rows) {
    $cells = $row -split "\|\|"
    $table += ,$cells
}

Can anyone provide guidance or recommendations and what a loop might look like to kick me in the right direction?

I am seeing guides telling me to build things like this:

$NewRow=@{ 'var1' = "0" ; 'var2' = "1" ; 'var3' = "2"; 'var4' = "3"}
$table.Add($NewRow) | Out-Null

However, I am failing to think of a proper loop that would work to consistently fill those values or if that is the right approach.

To clarify: I know this data format looks odd, but the possible data in the values can contain a ton of different delimiters, so || was by far the safest option given how I know how the data looks on a regular basis.

>Solution :

For each row, construct a single object by collecting all the property values in a dictionary/hashtable, then cast to [PSCustomObject]:

'0||1||2||3;a||b||c||d;10||11||12||13;'.Split(';') |Where-Object {$_} |ForEach-Object {
  # create dictionary to hold property values
  $properties = [ordered]@{}

  # keep track of property number
  $varCount = 1

  # add each individual value to its own property entry in the dictionary
  $_ -split '\|\|' |ForEach-Object {
    $properties["var${varCount}"] = $_
    $varCount++
  }

  # cast and output resulting object
  [PSCustomObject]$properties
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading