Powershell script with a path with square brackets in a string for

3.5k views Asked by At

I can't get my Powershell script to work with a path which has square brackets.

Input path is "c:\temp\yeah [thats it]"

param (  
    [string]$folderPath = $env:folderPath
 )
$folderPath = $folderPath + "\"

    Add-Content -Path $folderPath"01-playlist.m3u" -Value "a file name.mp3"

I looked at '-literalpath' and 'Convert-path' but I can't see how to implement that to my code.

2

There are 2 answers

1
Theo On BEST ANSWER

Simply use -LiteralPath instead of -Path.

Add-Content -LiteralPath "D:\Test\yeah [thats it]\01-playlist.m3u" -Value "a file name.mp3"

Now the path is taken literally, so you cannot use wildcards as you would with Path.

By the way, your optional parameter looks strange.. Unless you have set an environment variable for it, there is no such thing as $env:folderPath

Also, to combine a path and a filename, there is a cmdlet called Join-Path. Using that is far better than using constructs like $folderPath + "\" where it is very easy to either forget backslashes or adding too many of them..

Instead, I would write

$file = Join-Path -Path $folderPath -ChildPath '01-playlist.m3u'
Add-Content -LiteralPath $file -Value "a file name.mp3"
0
MikeK On

You need to use backticks I believe. If you are doing this from a shell this works "abc ````[123````].txt" Note the number of back ticks changes to two if you are wrapping with single quotes.

See this answer: https://superuser.com/questions/212808/powershell-bug-in-copy-move-rename-when-filename-contains-square-bracket-charac#:~:text=Getting%20PowerShell%20to%20correctly%20recognize,four%20backticks%20to%20escape%20it.