Home > OS >  Powershell how to parse array
Powershell how to parse array

Time:01-19

I have a microsoft form that submits an array of data to a variable that I need to process. The Output array from the forms looks like this and is assigned to a variable:

["a","b","c"]

How can I create an array in powershell from this so I can actually call the array items like this:

if ("a" in $array) {
     # Do something
}

if ("b" in $array) {
     # Do something
}

if ("c" in $array) {
     # Do something
}

CodePudding user response:

The output from your form, by the looks of it, is a Json string which you can convert to an object using ConvertFrom-Json:

$var = '["a","b","c"]'
$array = $var | ConvertFrom-Json

switch($array)
{
    a { 'a in array'; continue }
    b { 'b in array'; continue }
    c { 'c in array'; continue }
    Default { 'nothing found' }
}

Note, the use of the continue on above example is strictly for efficiency. From about_Switch documentation we can read the following:

The Break keyword stops processing and exits the Switch statement.

The Continue keyword stops processing the current value, but continues processing any subsequent values.

  •  Tags:  
  • Related