Ron
Ron

Reputation: 15501

Redirect the output of a PowerShell script to a file using command prompt

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.

Upvotes: 1

Views: 6449

Answers (2)

iRon
iRon

Reputation: 23623

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

Upvotes: 3

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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

Upvotes: 1

Related Questions