[英]passing \ in argument to powershell script causes unexpected escaping
这是我的 powershell 脚本 test.ps1:
Write-Output $args;
现在假设我有一个批处理脚本,它使用各种路径调用这个 powershell 脚本。 其中之一是c:\\
:
powershell -executionpolicy Bypass -file test.ps1 "c:\"
输出是:
C:”
有什么方法可以引用我的参数,以便 c:\\ 实际上会被采用并按原样存储在$args[0]
变量中? 我知道我可以通过传递"c:\\\\"
来解决这个问题,但这不是真正的解决方案。
编辑:在 test.ps1 中使用命名参数没有任何区别:
[CmdletBinding()]
param(
[string]$argument
)
Write-Output $argument;
EDIT2:使用批处理文件可以正常工作。
我的 test.bat 脚本:
echo %~1
我运行它:
test.bat "c:\"
很好地返回:
C:\\
您确定这是来自 powershell 而不是来自调用您的语句的程序吗? 反斜杠不是 powershell 中的转义码。
从 ise 运行时,我的 test.ps1 正在工作。
这对我有用:
powershell -executionpolicy Bypass -command "test.ps1 -argument 'C:\'"
(以双引号结尾)
PowerShell.exe 的帮助文件说:
文件必须是命令中的最后一个参数,因为在文件参数名称之后键入的“所有字符”都被“解释”为脚本文件路径后跟脚本参数。
您反对 Powershell.exe 的命令行解析器,它使用“\\”来转义引号。 你需要报价吗? 不是你的情况:
powershell -file test.ps1 c:\
印刷
c:\
同样,这也有效
powershell -file test.ps1 "c:\ "
c:\
但是你的 arg 有你想要修剪的额外空间。 顺便说一句,单引号在这里没有帮助:
powershell -file test.ps1 'c:\'
'c:\'
如果您需要将最后的反冲传递给命令,您可以使用
$ArgWithABackslashTemp = $ArgWithABackslash -replace '\\$','\\'
&$ExePath $ArgWithABackslashTemp
或者,如果 exe 足够聪明,可以在没有尾随反斜杠的情况下处理它
&$ExePath $ArgWithABackslash.trim('\')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.