Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using New-Item cmdlet with Literalpath in Powershell?

I'm using New-Item cmdlet to create a new folder and surprisingly find that it has no -Literalpath parameter available. My path contains square brackets in it. What can I do to address this problem?

like image 947
preachers Avatar asked Jan 31 '26 18:01

preachers


2 Answers

Yes, it is surprising that New-Item has no -LiteralPath parameter, especially given that:

  • its -Path parameter behaves like a -LiteralPath parameter, i.e. it treats the path as a literal (verbatim) one.

    • As for a potential future enhancement: While renaming the parameter isn't an option so as not to break backward compatibility, conceivably -LiteralPath could be introduced as an alias of -Path.
  • except if a -Name argument is also supplied, in which case the -Path argument is unexpectedly treated as a wildcard expression, which notably causes problems with file paths that contain [

    • This behavior should be considered a bug - see GitHub issue #17106

      • A related bug is that the path passed to the -Target (aka -Value) parameter too is interpreted as a wildcard expression - see this answer and GitHub issue #14534.
    • The workaround is to not use -Name and instead join the name component to the -Path argument, such as with Join-Path

# OK - with only a -Path argument, the path is taken *literally*
# Creates a subdir. literally named '[test]' with a file 'test.txt' in it.
New-Item -Force -Path '[test]\test.txt'

# !! BROKEN - with -Name also present, the -Path argument is
# !! interpreted as a *wildcard expression*
New-Item -Force -Path '[test]' -Name 'test.txt'

# WORKAROUND - use -Path only.
New-Item -Force -Path (Join-Path '[test]' 'test.txt')
like image 119
mklement0 Avatar answered Feb 02 '26 12:02

mklement0


So, it was a little bit confusing what was the actual problem. So, you need to escape the brackets, the same way you would escape "\n" in strings - with " ` ". This will create the folder:

> New-Item -Path 'C:\stuff\powershell\`[test`]' -Name "221" -ItemType "directory"

But this will "silently fail":

> New-Item -Path 'C:\stuff\powershell\[test]' -Name "221" -ItemType "directory"
like image 33
Bakudan Avatar answered Feb 02 '26 13:02

Bakudan