Write powershell output to file from within batch file

Abstract: Capture PowerShell console output to a file by redirecting standard output using the greater-than operator in the batch command line.

Created: 2026-08-04 by

To write PowerShell output to a file from a batch script, invoke the executable using powershell.exe with the -Command or -File parameter. Redirect the standard output stream using the > operator directly in the batch command line. This method captures all console text generated by the script and saves it to a specified path for logging or further processing.

Understanding the Execution Context

When you run a PowerShell command from a Windows Command Prompt (CMD) batch file, you are bridging two different shells. The batch file acts as the parent process, while PowerShell runs as a child process. By default, any text that PowerShell writes to its host window is considered standard output. In the world of Windows scripting, this output travels through a channel known as STDOUT. The challenge often arises when developers try to use redirection operators inside the PowerShell script itself rather than in the batch wrapper. While PowerShell has its own redirection syntax, it is generally cleaner and more reliable to handle the file writing at the batch level. This ensures that the batch file retains control over where the data goes, regardless of how complex the PowerShell logic becomes. It is also important to distinguish between success and error streams. Standard errors usually go to STDERR, which does not get captured by the basic > operator. If your goal is to capture everything, including potential error messages, you must explicitly merge these streams. However, for simple logging tasks where only successful execution data matters, the standard approach is sufficient. You can read more about handling unsynced outputs in our guide on Avoiding Unsynced STDOUT and STDERR Output File in Windows, which details why separating these streams prevents data loss during high-load operations.

The Basic Redirection Syntax

The most straightforward way to achieve this is by appending the redirection symbol to the end of your PowerShell invocation command. The syntax follows the standard CMD convention: powershell.exe -Command "Your-PowerShell-Code" > output.txt. Here is a minimal example. Suppose you want to list all running processes and save them to a text file named processes.log. Your batch file would contain the following line:
powershell.exe -Command "Get-Process | Select-Object Name, Id" > processes.log
In this scenario, the batch interpreter sees the > symbol. It creates the file if it does not exist, or truncates it if it does. Then, it pipes whatever comes out of the PowerShell window into that file. The user will see no output on their screen unless they remove the redirection. This is particularly useful for scheduled tasks where visual feedback is unnecessary but an audit trail is required. If you prefer to keep the original content and append new data instead of overwriting it, use the double greater-than symbol: >>. This is essential for log files that accumulate data over time. For instance, powershell.exe -Command "Write-Host 'Task Complete'" >> daily_log.txt adds a new line to the existing file without deleting previous entries.

Handling Spaces and Quotes

A common pitfall occurs when your PowerShell command contains spaces or special characters. The batch parser can become confused if quotes are not balanced correctly. Always wrap the entire PowerShell command string in double quotes if it contains single quotes internally, or vice versa. For example, if your command needs to pass a string argument, you might write:
powershell.exe -Command "Write-Output 'Hello World'" > result.txt
If the command is long, consider breaking it into a variable first to improve readability, though this requires careful escaping of variables within the batch environment.

Using PowerShell Script Files

While inline commands work well for short snippets, complex logic should reside in a separate .ps1 file. Invoking a script file is slightly different because you use the -File parameter instead of -Command.
powershell.exe -File C:\Scripts\MyScript.ps1 > output.txt
This approach offers better security and maintainability. You can edit the PowerShell script independently of the batch file. Furthermore, it allows you to use advanced PowerShell features like modules and dot-sourcing without worrying about CMD's limited parsing capabilities. Note that execution policy might block script files by default. You may need to include -ExecutionPolicy Bypass in your call if your environment restricts unsigned scripts. For scenarios where you are manipulating files based on specific criteria, such as copying files to unknown folders, understanding how to manage paths in both environments is crucial. See Batch File: Copy Specific File to Unknown Folder in Windows for insights on handling dynamic paths across shell boundaries.

Merging Error Streams

Sometimes, capturing only standard output is not enough. If a command fails, the error message might be lost if you only redirect STDOUT. To capture both success and failure logs, you can merge the streams. In CMD, you use the 2>&1 syntax.
powershell.exe -Command "Get-Item NonExistentFile" 2>&1 > combined.log
The 2>&1 tells the system to redirect stream 2 (errors) to stream 1 (standard output). The subsequent > then catches everything. This ensures that even if the PowerShell script encounters an exception, the stack trace is saved to your log file for debugging. Without this step, errors would still appear on the console while the file remained empty or partial.

Common Pitfalls and Best Practices

One frequent issue is encoding. By default, CMD uses the system's active code page, which might differ from UTF-8. If your PowerShell output contains non-ASCII characters, the file might appear garbled. You can force UTF-8 encoding by adding parameters to the PowerShell call or by configuring the CMD session beforehand. Another consideration is timing. Batch files execute sequentially. If you are writing to a file that another process reads immediately after, ensure there is no race condition. Closing the file handle is automatic upon completion of the PowerShell process, so this is rarely an issue for simple scripts. Finally, always test your redirection in a safe environment. Accidentally using > on a critical system file can overwrite important data. Double-check your file paths and permissions before deploying automation scripts to production servers.

Frequently Asked Questions

How do I append to a file instead of overwriting it?

Use the double greater-than operator (>>) instead of the single one. This adds new content to the end of the existing file rather than replacing its contents. For example, powershell.exe -Command "..." >> log.txt.

Why is my error message missing from the output file?

Error messages are sent to the STDERR stream, which is separate from STDOUT. The standard > operator only captures STDOUT. To include errors, you must merge the streams using 2>&1 before redirecting to the file.

Can I use variables in the file path?

Yes, you can use batch variables in the redirection target. Ensure the variable is expanded correctly by enclosing the path in quotes if it contains spaces, like > "%~dp0output.txt".

Does this work with PowerShell Core (v6+)?

Yes, the redirection syntax is handled by the CMD shell, not PowerShell itself. Therefore, it works identically whether you invoke powershell.exe or pwsh.exe.

What if the PowerShell command fails completely?

If the command fails, the exit code will be non-zero, but the redirection will still capture any text written to the console before the crash. Using 2>&1 ensures that error details are preserved in the log file for analysis.

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