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?
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.
-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
-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')
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With