September 25th, 2019

PowerTip: Converting a Here-String to an Array in One Line with PowerShell

Doctor Scripto
Scripter

Summary: Using the split method in a more powerful fashion to split an array based upon two line terminating types

A picture containing scissors Description automatically generated

Hey, Doctor Scripto. I was wondering if there was a more efficient way of converting a Here-String to an Array when there were multiple line termination options like Linefeed or Carriage Return and Linefeed?

There most definitely is. You can pass multiple parameters to the split method. This example traps both!

$HereStringSample=@’ Banana Raspberry ‘@

$HereStringSample.Split(@(“$([char][byte]10)”, “$([char][byte]10)”,”$([char][byte]13)”, [StringSplitOptions]::None))

PowerShell, Doctor Scripto, PowerTip, Paulo Morgado

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

2 comments

Discussion is closed. Login to edit/delete existing comments.

  • Nikolay Kozhemyak

    I suppose there is a mistake in the code example.
    The .split( ) method has multiple variations and the most common is char[].
    The options parameter '[StringSplitOptions]::None' is included in the array and the method recognizes it as one of the elements of the array.
    However, the meaning is different to put it as the option.

    Nevertheless, the use of NONE here does not help achieve the goal.
    The better option would be [StringSplitOptions]::RemoveEmptyEntries, because if...

    Read more
  • Thomas Brevig

    I use this every day:

    $array = @”
    Banana
    Raspberry
    “@ -split ‘\r\n’

    Double quotes allow for variables inside the here-string
    I find it so handy that I made a snippet for it in vscode

    “Here-String to Array”: {
    “prefix”: “Here-String to Array”,
    “body”: [
    “$${1:arrayname} = @\””,
    “${2:string}$0”,
    “\”@ -split ‘\\r\\n'”
    ],
    “description”: “Here-String to Array”
    }