Summary: Using the split method in a more powerful fashion to split an array based upon two line terminating types
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
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...
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”
}