1

How to redirect the output of a PowerShell 5.0 script to a file using cmd in Windows 10? I tried the following:

powershell ".\myscript.ps1 | Out-File outfile.txt"

and:

powershell .\myscript.ps1 > outfile.txt

to no avail. The outfile.txt is created but remains empty. The command prompt window is run with Administrator privileges.

In a script I use:

Write-Host $MyVar
Write-Host $SomeOtherVar

to output the values to a screen.

9
  • I'm not an expert, but isn't there the option -Command missing? Commented Jul 11, 2019 at 9:29
  • What is being outputted from your .ps1? Commented Jul 11, 2019 at 9:31
  • @I.TDelinquent Some internal info. It works as expected when run as-is and displays the output in the powershell console as expected. I would like to redirect this output to a file using cmd. Commented Jul 11, 2019 at 9:32
  • 1
    @Ron Does myscript.ps1 make use of Write-Host? That won't be redirected in any case Commented Jul 11, 2019 at 9:44
  • @MathiasR.Jessen Indeed it does. Commented Jul 11, 2019 at 9:45

2 Answers 2

3

Use the specific PowerShell redirection operators:
(they appear to work at the (cmd) command prompt as wel)

Redirect the success stream (1>):

powershell .\myscript.ps1 1> outfile.txt

Redirect all streams (*>):

powershell .\myscript.ps1 *> outfile.txt
Sign up to request clarification or add additional context in comments.

Comments

1

In a script I use:

Write-Host $MyVar
Write-Host $SomeOtherVar

to output the values to a screen.

Yeah, that's your problem right there! Write-Host writes the information straight to the screen buffer of the host application, so the standard output stream will never actually see anything.

Change your Write-Host statements to Write-Output (or just remove them):

Write-Output $MyVar
Write-Output $SomeOtherVar
# or simply
$MyVar
$SomeOtherVar

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.