1
 $path = "\path\to\my\file"

I want to simply remove the first \ how do I do that?

I don't want to remove the first character if it's a letter, only if it's \

whoisearth
  • 4,080
  • 13
  • 62
  • 130

2 Answers2

7
$path = $path.TrimStart("\")

Would convert $path to path\to\my\file

Take note that subsequent leading backlashes would also be removed as well, so if you had \\\path it would be reduced to path!

gravity
  • 2,175
  • 2
  • 26
  • 34
  • 3
    you may want to mention that the `.Trim()` variants trim the _characters as individual chars_ in the parens ... and trim ALL OF THEM. so, your code would trim away **_all_** the leading backslash characters. that is fine when you expect it ... but truly disconcerting when it happens unexpectedly. [*grin*] – Lee_Dailey Jul 02 '19 at 21:15
  • ... as I [noticed](https://stackoverflow.com/questions/70171826/archive-folder-without-some-subfolders-and-files-using-powershell/70173927#70173927) while trying to trim `.\` from a relative path when zipping. – Rich Moss Dec 02 '21 at 19:07
2

You could use the regex -replace operator:

$path = $path -replace '^\\'

This will remove exactly 1 backslash from the start of the string

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206