【发布时间】:2012-12-10 07:38:23
【问题描述】:
脚本是为 CLI 编写的,在 Microsoft 世界中,引用文件的脚本参数可能经常有空格,需要引用它们。
这对我来说是个问题。考虑这个脚本:
#testarg.ps1
for($i=0; $i -lt $args.length; $i++)
{
write-host "Arg$i = $($args[$i])"
}
如果我在 PowerShell 交互环境中运行它,像这样:
PS C:\script> .\testarg.ps1 "first arg" "second arg"
正如预期的那样,我得到了,
Arg0 = first arg
Arg1 = second arg
但是,在交互模式之外,脚本的普通使用是批量使用的。据我了解,从cmd.exe 运行脚本的the Microsoft suggested way 似乎是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 选项,双引号可以正常工作。这表明可以将 ps1 文件(带有 FTYPE.exe)的 Windows 文件类型关联重新映射为:
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。
【问题讨论】:
标签: powershell parameters quotes