Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting standard input\output in Windows PowerShell

What is the required syntax to redirect standard input/output on Windows PowerShell?

On Unix, we use:

$./program <input.txt >output.txt 

How do I execute the same task in PowerShell?

like image 556
Nitin Avatar asked Jul 12 '12 08:07

Nitin


People also ask

How do I redirect output in PowerShell?

There are two PowerShell operators you can use to redirect output: > and >> . The > operator is equivalent to Out-File while >> is equivalent to Out-File -Append . The redirection operators have other uses like redirecting error or verbose output streams.

How do I use redirection operator in PowerShell?

The Redirection operators are used in PowerShell to redirect the output from the PowerShell console to text files. PowerShell supports the following redirection operators: > >>

What is meant by redirecting input output?

On a command line, redirection is the process of using the input/output of a file or command to use it as an input for another file. It is similar but different from pipes, as it allows reading/writing from files instead of only commands.


2 Answers

You can't hook a file directly to stdin, but you can still access stdin.

Get-Content input.txt | ./program > output.txt 
like image 152
JasonMArcher Avatar answered Sep 22 '22 18:09

JasonMArcher


If there is someone looking for 'Get-Content' alternative for large files (as me) you can use CMD in PowerShell:

cmd.exe /c ".\program < .\input.txt" 

Or you can use this PowerShell command:

Start-Process .\program.exe -RedirectStandardInput .\input.txt -NoNewWindow -Wait 

It will run the program synchronously in same window. But I was not able to find out how to write result from this command to a variable when I run it in PowerShell script because it always writes data to the console.

EDIT:

To get output from Start-Process you can use option

-RedirectStandardOutput

for redirecting output to file and then read it from file:

Start-Process ".\program.exe" -RedirectStandardInput ".\input.txt" -RedirectStandardOutput ".\temp.txt" -NoNewWindow -Wait $Result = Get-Content ".\temp.txt" 
like image 33
Siarhei Kavaleuski Avatar answered Sep 24 '22 18:09

Siarhei Kavaleuski