Search code examples
arrayspowershellsplitpowershell-3.0pipeline

Create and split an array twice all inline in Powershell


I have the following code which works but I am looking for a way to do this all inline without the need for creating the unnecessary variables $myArray1 and $myArray2:

$line = "20190208 10:05:00,Source,Severity,deadlock victim=process0a123b4";
$myArray1 = $line.split(",");
$myArray2 = $myArray1[3].split("=");
$requiredValue = $myArray2[1];

So I have a string $line which I want to:

  1. split by commas into an array.
  2. take the fourth item [3] of the new array
  3. split this by the equals sign into another array
  4. take the second item of this array [1]
  5. and store the string value in a variable.

I have tried using Select -index but I haven't been able to then pipe the result and split it again.

The following works:

$line.split(",") | Select -index 3 

However, the following results in an error:

$line.split(",") | Select -index 3 | $_.split("=") | Select -index 1

Error message: Expressions are only allowed as the first element of a pipeline.


Solution

  • $line.Split(',')[3].Split('=')[1]