使用所有参数从批处理文件调用PowerShell脚本 [英] Call PowerShell Script From Batch File With All Parameters
问题描述
此问题和
This question and this blog post address how to pass particular parameters into a PowerShell script from a batch file.
如何将所有参数传递到PowerShell脚本中?基本上,我想使用所有参数,以便批处理文件透明地传递所有参数.
How can one pass all parameters into the PowerShell script? Basically I want to splat all the parameters so that the batch file passes all arguments through transparently.
编辑以获取更多上下文:
我当前正在使用这样的一行:
I'm currently using a line like:
PowerShell.exe -Command "& '%~dpn0.ps1' '%1' '%2'"
这可行,但是会在文件之间创建冗余,因此,如果我更新PowerShell脚本以采用不同的参数,则也必须更新批处理脚本.好的,如果我可以做类似的事情:
This works, but creates a redundancy between the files such that, if I update the PowerShell script to take different arguments, I have to update the batch script as well. What would be nice is if I could do something like:
PowerShell.exe -Command "& '%~dpn0.ps1' '%*'"
推荐答案
尝试以下操作:
powershell -File "%~dpn0.ps1" %*
-
在批处理文件中,
%*
代表所有传递的参数. [1]In batch files,
%*
represents all arguments passed.[1]-File
是用于通过PowerShell的CLI调用脚本的参数.-File
is the parameter to use to invoke scripts via PowerShell's CLI.[1]请注意,要使
cmd.exe
(批处理文件)识别带有嵌入式空格作为单个参数的参数,必须将其括在"..."
中.
例如,如果要将参数a
和b c
传递给批处理文件file.cmd
,则必须将其称为
file a "b c"
.
要传递嵌入式"
实例,请\
-对其进行转义;例如,"\"b c\""
使PowerShell看到"b c"
,包括双引号.
如果遵守这些规则,则%*
-不带引号-正确地传递参数数组.
不不使用"%*"
-它将无法按预期工作.[1] Note that for
cmd.exe
(batch files) to recognize an argument with embedded whitespace as a single argument, you must enclose it in"..."
.
For instance, if you wanted to pass argumentsa
andb c
to batch filefile.cmd
, you'd have to call it as
file a "b c"
.
To pass embedded"
instances,\
-escape them; e.g.,"\"b c\""
makes PowerShell see"b c"
, including the double quotes.
If you respect these rules,%*
- without quoting - properly passes the array of arguments through.
Do not use"%*"
- it won't work as expected.[2]实际上,
-Command
导致所有以下所有参数均由单个空格连接,然后将结果字符串解释为 PowerShell命令-也就是说,参数由cmd.exe
(批处理文件)的规则解析后,它们将由PowerShell进行另一轮 解析.
不幸的是,PowerShell一直以这种方式工作,但是由于PowerShell已跨平台运行,因此行为晦涩难懂,并且有可能在Unix世界中引起更多混乱-请参阅[2] In effect,
-Command
causes all following arguments to be joined by a single space each, and the resulting string is then interpreted as a PowerShell command - that is, after the arguments are parsed by the rules ofcmd.exe
(batch files), they are subject to another round of parsing, by PowerShell.
Unfortunately, PowerShell has always worked this way, but the behavior is obscure, and is likely to cause even more confusion in the Unix world, now that PowerShell has gone cross-platform - see this GitHub issue.这篇关于使用所有参数从批处理文件调用PowerShell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!