對CLI進行腳本編寫,並且在Microsoft世界中,引用文件的腳本參數通常可能有空格,要求引用它們。將引用參數傳遞給PowerShell腳本
事實證明,這對我來說是有問題的。如果我運行PowerShell的互動環境中,這樣的
#testarg.ps1
for($i=0; $i -lt $args.length; $i++)
{
write-host "Arg$i = $($args[$i])"
}
:考慮這個腳本
PS C:\script> .\testarg.ps1 "first arg" "second arg"
我得到的,符合市場預期,
Arg0 = first arg
Arg1 = second arg
但普通使用的在交互模式之外,腳本將在批處理模式之外。據我所知,the Microsoft suggested way運行腳本cmd.exe
似乎是powershell.exe path\to\script.ps1
(沒有空間的路徑)。但是:
powershell.exe .\testarg.ps1 "first arg" "second arg"
給出了不一致的結果:
Arg0 = first
Arg1 = arg
Arg2 = second
Arg3 = arg
我注意到,以獲得預期的結果,我可以使用單引號:
powershell.exe .\testarg.ps1 'first arg' 'second arg'
但是這往往是不可行的時候腳本將由自動生成和傳遞參數的GUI工具運行,並且/或者在出現更多CLI工具時使用引號來保持一致性。
出於某種原因,使用-file
選項時:
powershell.exe –file .\testarg.ps1 "first arg" "second arg"
::(reference to relative path '.\' is optional)
我再次得到預期的結果:
Arg0 = first arg
Arg1 = second arg
與
-file
選項的雙引號正常工作
左右。這表明,一個可以重新映射Windows文件類型關聯的ps1
文件(FTYPE.exe
)喜歡的東西:
FTYPE Microsoft.PowerShellScript.1=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -file "%1" %*
鑑於FTYPE協會,我可以簡單地寫取得預期的結果:
testarg.ps1 "first arg" "second arg"
後者是對我很滿意,但因爲我是新手使用PowerShell,我想知道:
- 對於一般的腳本,是批量形式
powershell.exe –file path\to\script.ps1
和交互式表單(來自PowerShell內)PS > path\to\script.ps1
等效?有兩種形式可能會產生不同的輸出/效果嗎? - 腳本內部是否有可能的解決方案來讀取命令行(不刪除雙引號)?像
*%
爲cmd.exe
。
它從內'cmd.exe'意關聯後'Microsoft.PowerShellScript.1輸入PowerShellScript.exe。無論如何,我重寫了我的原始問題,使其更清晰。 – antonio
在命令提示符下,'powershell -f testarg.ps1'first arg「」second arg「'是要走的路。僅供參考,「powershell。\ testarg.ps1」「」「第一個參數」「」「」「第二個參數」「」「恰好也產生了相同的結果;這將無助於您的文件類型關聯,但... – mousio