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 the2>&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.