Run Powershell command from cmd with parameters

Abstract: Resolve syntax errors when passing parameters to PowerShell scripts from the Windows Command Prompt by using correct quoting and the call operator.

Created: 2026-08-02 by
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 "&amp; '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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More