How to access file paths in Powershell containing special characters?

前端 未结 3 874
感动是毒
感动是毒 2021-01-02 00:19

I am calling powershell from within a Java application (thru the Windows command prompt) to read various file attributes.

e.g.

powershell (get-item \         


        
3条回答
  •  猫巷女王i
    2021-01-02 00:42

    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 
    

提交回复
热议问题