将引用的参数传递给PowerShell脚本
脚本是为CLI编写的,在Microsoft世界中,引用文件的脚本参数通常会有空格,需要引用它们 这对我来说是个问题。考虑这个脚本:将引用的参数传递给PowerShell脚本,powershell,parameters,quotes,Powershell,Parameters,Quotes,脚本是为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" 正如
#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
运行脚本似乎是powershell.exe path\to\script.ps1
(路径中没有空格)。但是:
给出了不一致的结果:
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
文件的Windows文件类型关联(使用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的*%
当你写信的时候,有一件事我不明白:
testarg.ps1 "first arg" "second arg"
你把它叫做哪一批
从PowerShell.exe
,应将其写入:
cd "c:\Temp"
& .\testarg.ps1 "first arg" "second arg"
powershell –file .\testarg.ps1 "first arg" "second arg"
从cmd.exe
中,应写入:
cd "c:\Temp"
& .\testarg.ps1 "first arg" "second arg"
powershell –file .\testarg.ps1 "first arg" "second arg"
在将Microsoft.PowerShellScript.1类型关联到PowerShellScript.exe后,它将从
cmd.exe
中创建。无论如何,我重写了我原来的问题以使其更清楚。在命令提示符下,powershell-f testarg.ps1“first arg”“second arg”是解决方法。但是,仅供参考,powershell。\testarg.ps1““第一个参数”“第二个参数”
碰巧也会产生相同的结果;这对您的文件类型关联没有帮助,但是…