I am trying to run a batch file from powershell. I would like to get the response but it is failing. If I run the .bat file:
rabbitmqctl.bat -n rabbit@xxx-123 ping
I get the following response:
Ping succeeded
However when I run it through powershell:
$test = Start-Process -FilePath "C:\Program Files\RabbitMQ\rabbitmq_server-3.10.7\sbin\rabbitmqctl.bat" -WindowStyle Hidden -ArgumentList "-n rabbit@xxx-123 ping" -Wait -PassThru;
$test
variable is empty.
Any help?
To synchronously execute console applications or batch files in the current console window, call them directly.
$LASTEXITCODE
variable.Do not use Start-Process
(or the System.Diagnostics.Process
API it is based on), except if truly necessary.
Specifically, you can not directly capture the output from an executable launched from a Start-Process
call; the only in-memory output you can capture - assuming you use the -PassThru
switch - is a System.Diagnostics.Process
instance describing the launched process.
GitHub docs issue #6239 provides guidance on when use of Start-Process
is and isn't appropriate.
Therefore:
$test =
& 'C:\Program Files\RabbitMQ\rabbitmq_server-3.10.7\sbin\rabbitmqctl.bat' -n rabbit@xxx-123 ping
Note:
Generally, you can call executables and batch files with arguments as you would from cmd.exe
, though there are some PowerShell-specific requirements:
Because your specific batch-file path requires quoting, use of &
, the call operator, is needed (you may choose to always use it, but it is only necessary for commands (executable paths) that are quoted and/or contain variable references.
For executables / batch files located in the current directory, a notable difference between cmd.exe
and PowerShell is that the latter - by security-minded design - requires your to explicitly signal the intent to invoke the file there, using prefix .\
(or ./
); e.g. while cmd.exe
allows you to use rabbitmqctl.bat
to invoke a batch file by that name in the current directory, PowerShell requires .\rabbitmqctl.bat
PowerShell's variable references, string literals and escaping rules differ from cmd.exe
:
PowerShell supports two kinds of quoted string literals, expandable (double-quoted) strings ("..."
) and verbatim (single-quoted) strings ('...'
)
PowerShell's escape character is `
, the so-called backtick, where cmd.exe
uses ^
Variable references in PowerShell use sigil $
and distinguish between PowerShell-only and environment variables (e.g, $foo
and $env:USERPROFILE
), compared to cmd.exe
, which knows only environment variables and uses %...%
syntax (e.g. %USERPROFILE%
)
Compared to cmd.exe
, PowerShell has different and more metacharacters (characters with special meaning), notably $ @ { } , ; ( ) `
. These enable many advanced features.