Reputation: 55
I am trying to run several PowerShell commands from a batch script, however the "%" symbol does not get transferred to PowerShell.
For example, writing the following in a command prompt window:
powershell -Command "& {echo 'per%entage'}"
Will print:
per%entage
which is what I want, however if I save the same command into a .bat or .cmd file, it instead prints:
perentage
Why is it ignoring the "%" symbol? Is there a way to make it transfer properly? I'm especially confused that it works in a command prompt window, but not in a batch script. You'd think both would either work or not work.
Upvotes: 0
Views: 91
Reputation: 437618
Very unfortunately, cmd.exe
's behavior differs with respect to command invocations from an interactive prompt vs. from a batch file with respect to how %
characters are interpreted.
See this answer for background information.
Therefore, when calling from a batch file, a %
char. that is to interpreted verbatim, must be escaped as %%
:
:: From a *batch file*.
powershell -Command "'per%%entage'"
Note:
echo
is a built-in alias for the Write-Output
cmdlet, whose explicit use is rarely needed - see this answer for more information.
Invocation of commands (symbolized as ...
here) in the form & { ... }
is virtually never needed when using the PowerShell CLI - just use ...
as-is.
Generally, for predictable invocation, it's worth using the -NoProfile
switch as well - before the -Command
parameter - so as to bypass loading of PowerShell's profile files, which are primarily meant for interactive sessions.
Upvotes: 2