11

Why does the string for the -split parameter require two backslashes while the string for the -join parameter requires only one backslash? The backtick is the escape character in Powershell. What does a backslash preceding a character do for you?

$path = 'C:\folder\test\unit1\testing\results\report.txt'

$path -split '\\' -notlike '*test*' -join '\'

http://powershell.com/cs/blogs/tips/archive/2014/06/17/fun-with-path-names.aspx

John Koerner
  • 37,428
  • 8
  • 84
  • 134
lit
  • 14,456
  • 10
  • 65
  • 119

2 Answers2

11

-split splits on a regex by default. So it is the regex that requires escaping a backslash. You can tell PowerShell not to use a regex like so:

$path -split '\',-1,'SimpleMatch'

-join is just taking whatever characters you supply to use as the delimiter to stick between the strings being joined.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • To anyone wondering, `-split` can take up to 3 parameters: ``, ``, ``, so in Powershell <7.0, `-split '\', -1, 'SimpleMatch'` means to split on `\\`, return _all_ matches (max-substrings of 0 or lower returns all in PS <7.0), and use SimpleMatch instead of the default RegexMatch. Reference: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split?view=powershell-7.3 – Prid Aug 24 '23 at 20:21
3

-split is accepting a regular expression where backslash is special character, so it need to be escaped

Novakov
  • 3,055
  • 1
  • 16
  • 32