0

Can anyone explain the strange behavior with string.split given the following examples.

# produces output that appears to split on "n" rather than the newline character
(ls alias: | Out-String).Split("\n")

# produces output that appears to split on "r" or "n" rather than the windows newline characters
(ls alias: | Out-String).Split("\r\n")

# produces output where each item is separated by a newline
(ls alias: | Out-String).Split([environment]::NewLine)

# produces the desired result
(ls alias: | Out-String) -split "\n"
# or
(ls alias: | Out-String) -split "\r\n"

I understand the difference between "\r\n" and "\n". I'm having trouble with the difference between -split and .Split(). I can't seem to find an answer.

galford13x
  • 2,483
  • 4
  • 30
  • 39
  • `-split` supports regex. `.Split()` does not but it does have some other overloads that are useful like the number of elements to return. It also splits on every character supplied iirc – Matt Jul 22 '17 at 17:50
  • 1
    NB. Backslash is not a PowerShell escape character, `"\n"` is not anything significant in PowerShell, you need `"\`n"` – TessellatingHeckler Jul 22 '17 at 19:27

0 Answers0