To run a PowerShell command with parameters from the Windows Command Prompt (cmd), use the
powershell.exe executable followed by the
-Command or
-c flag. Enclose your entire script block and arguments in double quotes to ensure cmd parses them correctly as a single argument. This method allows you to leverage PowerShell's advanced capabilities, such as object manipulation and .NET integration, directly within legacy batch environments without requiring a full PowerShell session.
Basic Syntax for Execution
The most straightforward way to invoke PowerShell is by calling the executable located in the system directory. The standard syntax involves specifying the command to execute immediately after the flag. Because cmd interprets special characters differently than PowerShell, proper quoting is essential to prevent parsing errors.
powershell.exe -Command "<Your-Script-Block>"
For example, if you want to retrieve the current date and time, you would type:
powershell.exe -Command "Get-Date"
This command launches a new PowerShell process, executes the specified cmdlet, outputs the result to the console, and then terminates the process. This ephemeral nature is often desirable for simple tasks where you do not need to maintain state between multiple commands.
Handling Parameters and Arguments
When passing parameters to PowerShell scripts or cmdlets, you must be careful with how cmd handles spaces and special characters. If your command includes arguments that contain spaces, wrap the entire string in double quotes. Inside those double quotes, you can use single quotes for PowerShell strings if necessary, or escape inner double quotes.
Consider a scenario where you are running a script file rather than an inline command. You might want to pass a path that contains spaces.
powershell.exe -Command "& 'C:\Path With Spaces\script.ps1' -Argument1 'Value 1'"
Notice the use of the call operator
& before the script path. This tells PowerShell to treat the string as a command to execute. Without it, PowerShell might interpret the path as a literal string rather than an executable script. Additionally, using single quotes around the path ensures that cmd does not split the argument at the space, while the double quotes around the whole expression keep cmd happy.
If you are passing complex objects or JSON data as a parameter, you may need to escape internal double quotes. In cmd, you typically cannot escape double quotes inside a double-quoted string easily. A common workaround is to use the
$args automatic variable or define variables inside the PowerShell block first.
powershell.exe -Command "$json = '{\"key\":\"value\"}'; Write-Output $json"
In this example, the backslashes escape the double quotes for PowerShell, allowing the JSON string to be constructed correctly before being outputted.
Retrieving Exit Codes and Errors
One of the critical aspects of integrating cmd with PowerShell is error handling. By default, if a PowerShell command fails, the cmd prompt may not reflect the failure status unless you explicitly check it. To capture the exit code of the PowerShell process, you should use the
$LASTEXITCODE variable or check the return value of the command.
However, PowerShell scripts often throw exceptions rather than setting traditional exit codes. To ensure that cmd receives a proper non-zero exit code on failure, you can structure your command to catch errors.
powershell.exe -Command "try { & 'script.ps1' } catch { exit 1 }"
This pattern attempts to run the script. If an exception occurs, the catch block executes, and the
exit 1 command terminates the PowerShell process with an error code. In cmd, you can then check
%ERRORLEVEL% to determine if the operation succeeded.
powershell.exe -Command "& 'deploy.ps1'"
if %ERRORLEVEL% NEQ 0 (
echo Deployment failed
) else (
echo Deployment successful
)
This approach provides robust error handling for batch files that rely on PowerShell for specific tasks. It bridges the gap between the two shells, ensuring that failures in one do not go unnoticed by the other.
Common Pitfalls and Best Practices
There are several common issues developers encounter when mixing cmd and PowerShell. Understanding these pitfalls can save significant debugging time.
- Quoting Issues: Nested quotes are the most frequent source of errors. Always test your command in a standalone PowerShell window first to verify the syntax, then translate it to the cmd-compatible format.
- Execution Policy: By default, PowerShell may have an execution policy that prevents script execution. If you receive an error stating that scripts are disabled, you may need to include
-ExecutionPolicy Bypass in your command.
powershell.exe -ExecutionPolicy Bypass -Command "& 'script.ps1'"
While bypassing the execution policy is convenient for testing, it poses security risks in production environments. Consider signing your scripts or configuring group policies to allow signed scripts instead.
Another pitfall involves character encoding. If your script or arguments contain non-ASCII characters, ensure that both cmd and PowerShell are using compatible encodings. Mismatches can lead to garbled text or command failures. Setting the code page in cmd using
chcp 65001 (UTF-8) can sometimes help, but it requires careful coordination with PowerShell's internal encoding settings.
For more information on managing drive contexts between these two shells, see
Command Prompt Drive Switching Different From PowerShell. This highlights how environment states differ and why explicit context management is sometimes required.
Advanced Scripting Scenarios
In more complex scenarios, you might need to pass dynamic values generated in cmd to PowerShell. You can achieve this by using cmd variables within the PowerShell command string. However, you must be cautious about expansion order. Cmd expands its variables before passing the string to PowerShell.
set MY_VAR=hello
powershell.exe -Command "Write-Output '%MY_VAR%'"
Here, cmd replaces
%MY_VAR% with
hello before PowerShell sees it. PowerShell then receives the command
Write-Output 'hello'. This works well for simple string substitution. For more complex data structures, consider writing the data to a temporary file and having PowerShell read from it, or using named pipes if performance is critical.
If you are dealing with linked files or shortcuts, understanding how to manipulate their targets programmatically is also useful. See
How to Set the Target of a .lnk File Programmatically with PowerShell or C++ for techniques that often complement these command-line invocation strategies.
Frequently Asked Questions
Why does my PowerShell command fail when run from cmd?
Most failures are due to incorrect quoting or execution policy restrictions. Ensure that your entire command is wrapped in double quotes for cmd, and use single quotes or escaped quotes internally for PowerShell. Additionally, verify that the execution policy allows the script to run, possibly by adding the
-ExecutionPolicy Bypass flag.
Can I pass multiple commands in a single PowerShell invocation?
Yes, you can separate multiple PowerShell statements with semicolons inside the command string. For example,
powershell.exe -Command "Get-Date; Get-Process" will execute both cmdlets sequentially. This is useful for chaining operations without launching multiple processes.
How do I handle spaces in file paths when invoking PowerShell from cmd?
Wrap the entire command in double quotes and use single quotes around the file path inside PowerShell. Use the call operator
& to execute the script. For instance,
powershell.exe -Command "& 'C:\My Folder\script.ps1'" ensures that the space is treated as part of the path rather than a delimiter.
What is the difference between -Command and -File flags?
The
-Command (or
-c) flag executes a string of PowerShell code, which is ideal for inline commands. The
-File (or
-f) flag executes a script file directly, which is better for longer, stored scripts. When using
-File, you can pass arguments directly after the script path without needing the call operator.
Does running PowerShell from cmd create a new process each time?
Yes, each invocation of
powershell.exe creates a new, isolated process. This means that variables, aliases, and module states defined in one invocation are not available in the next. If you need persistent state, consider keeping a long-running PowerShell session open or using shared files for data exchange.