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

Doctor Scripto

Dr Scripto

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

Doctor Scripto
Dr Scripto

Scripter, PowerShell, vbScript, BAT, CMD

Follow Dr Scripto   

2 comments

  • Thomas Brevig
    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”
    }

  • Nikolay Kozhemyak
    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 you have both of the linefeed and carriage return, it produces empty lines.

    Hence, the right code example could be like this:
    # Fixed Example
    $HereStringSample.Split(@(“$([char][byte]10)”, “$([char][byte]13)”), [StringSplitOptions]::RemoveEmptyEntries)

    # Simplest one
    $HereStringSample.Split(@(“`r”, “`n”), [StringSplitOptions]::RemoveEmptyEntries)

    # Also possible if you set that it is char array
    $HereStringSample.Split([char[]] “`r`n”, [StringSplitOptions]::RemoveEmptyEntries)

Leave a comment