How to access file paths in Powershell containing special characters?

If you can write the path to a temporary .txt file, the following works OK:

(Get-Item -literalpath (gc 'C:\Temp\path.txt')).creationTime

The file @ C:\Temp\path.txt contains the path with special characters in it, other than this I think you would have to escape each special character on a per path basis.

In addition to the hack above, it appears PowerShell V3 may help out here with the addition of a new 'magic parameter' language feature. Specifically, see the section headed 'Easier Reuse of Command Lines From Cmd.exe' here and because I hate link-rot, here it is, shamelessly reproduced below:

Easier Reuse of Command Lines From Cmd.exe

The web is full of command lines written for Cmd.exe. These commands lines work often enough in PowerShell, but when they include certain characters, e.g. a semicolon (;) a dollar sign ($), or curly braces, you have to make some changes, probably adding some quotes. This seemed to be the source of many minor headaches.

To help address this scenario, we added a new way to “escape” the parsing of command lines. If you use a magic parameter --%, we stop our normal parsing of your command line and switch to something much simpler. We don’t match quotes. We don’t stop at semicolon. We don’t expand PowerShell variables. We do expand environment variables if you use Cmd.exe syntax (e.g. %TEMP%). Other than that, the arguments up to the end of the line (or pipe, if you are piping) are passed as is. Here is an example:

 echoargs.exe --% %USERNAME%,this=$something{weird}
 Arg 0 is <jason,this=$something{weird}>

This is really a question about cmd.exe string escaping, then. Combining cmd and PowerShell string escaping is a total nightmare. After quite a few attempts, I got your specific example to work:

powershell.exe -nologo -noprofile -command ^&{ dir -LiteralPath ^"""".\`$ & ' [].txt"" }

    Directory: C:\Users\latkin
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         8/23/2012   8:46 AM          0 $ & ' [].txt

Totally intuitive, right?

You can spend 15 minutes wrestling with escape sequences every time, or you can try some other approaches.

Put the file name in a text file, and read it out of there.

powershell.exe -command "&{dir -literal (gc .\filename.txt)  }"

or

Use a script

powershell.exe -file .\ProcessFiles.ps1  # In processfiles.ps1 you are in fully powershell environment, so escaping is easier

or

Use -EncodedCommand

See powershell.exe -? (last item shown) or http://dmitrysotnikov.wordpress.com/2011/07/06/passing-parameters-to-encodedcommand/

Tags:

Powershell