简体   繁体   中英

passing \ in argument to powershell script causes unexpected escaping

This is my powershell script test.ps1:

Write-Output $args;

Now suppose I have a batch script that calls this powershell script with all kinds of paths. One of those is c:\\ :

powershell -executionpolicy Bypass -file test.ps1 "c:\"

The output is:

c:"

Is there any way to quote my arguments such that c:\\ would actually be taken and stored as is in the $args[0] variable? I know I can solve this quick'dirty by passing "c:\\\\" , but that's not a real solution.

EDIT: using named parameters in test.ps1 doesn't make any difference:

[CmdletBinding()]
param(
    [string]$argument
)
Write-Output $argument;

EDIT2: using a batch file instead works fine.

My test.bat script:

echo %~1

I run it:

test.bat "c:\"

Returns nicely:

c:\\

Are you sure this comes form powershell and not from the program which invokes your statement? The backslash is no escape code in powershell.

my test.ps1 is working, when run from ise.

this works for me:

powershell -executionpolicy Bypass -command "test.ps1 -argument 'C:\'"

(end with quote double-quote)

Help file for PowerShell.exe says:

File must be the last parameter in the command, because 'all characters' typed after the file parameter name are "interpreted" as the script file path followed by the script parameters.

You are against Powershell.exe's command line parser, which uses "\\" to escape quotes. Do you need quotes? Not in your case:

powershell -file test.ps1 c:\

prints

c:\

Similarly, this works too

powershell -file test.ps1 "c:\ "
c:\

but then your arg has that extra space which you would want to trim. BTW, Single quotes do not help here:

powershell -file test.ps1 'c:\'
'c:\' 

If you need the final backlash to be passed to the command, you can use

$ArgWithABackslashTemp = $ArgWithABackslash -replace '\\$','\\'
&$ExePath $ArgWithABackslashTemp

Or, if the exe is smart enough to handle it without the trailing backslash

&$ExePath $ArgWithABackslash.trim('\')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM