[英]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.