Call PowerShell Script From Batch File With All Parameters
Try the following:
powershell -File "%~dpn0.ps1" %*
In batch files,
%*
represents all arguments passed.[1]-File
is the parameter to use to invoke scripts via PowerShell's CLI.- All remaining arguments are then passed through as as-is (whereas
-Command
would subject them to another round of interpretation by PowerShell[2] ).
[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 arguments a
and b c
to batch file file.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] 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 of cmd.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.
jtpereyda
Maintainer of boofuzz. "If you're going to make a backward-compatibility-breaking change, no time is better than now; things will be worse in the future." Eric Lippert Sharp Regrets: Top 10 Worst C# Features
Updated on June 21, 2022Comments
-
jtpereyda about 2 years
This question and this blog post address how to pass particular parameters into a PowerShell script from a batch file.
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.
Edit for more context:
I'm currently using a line like:
PowerShell.exe -Command "& '%~dpn0.ps1' '%1' '%2'"
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' '%*'"