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.

Ron
  • 14,674
  • 4
  • 34
  • 47
  • I'm not an expert, but isn't there the option `-Command` missing? – aschipfl Jul 11 '19 at 09:29
  • What is being outputted from your .ps1? – I.T Delinquent Jul 11 '19 at 09: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`. – Ron Jul 11 '19 at 09:32
  • 1
    @Ron Does `myscript.ps1` make use of `Write-Host`? That won't be redirected in any case – Mathias R. Jessen Jul 11 '19 at 09:44
  • @MathiasR.Jessen Indeed it does. – Ron Jul 11 '19 at 09:45
  • Have you tried `powershell -file myscript.ps1 > outfile.txt`? Otherwise I'd suggest posting a sample script with which this behavior is reproducable (I'm unable to) – Mathias R. Jessen Jul 11 '19 at 09:46
  • Possible duplicate of [How to redirect the output of a PowerShell to a file during its execution](https://stackoverflow.com/questions/1215260/how-to-redirect-the-output-of-a-powershell-to-a-file-during-its-execution) – iRon Jul 11 '19 at 10:33
  • @iRon I need a redirection when using the `cmd`. – Ron Jul 11 '19 at 10:51
  • From the accepted answer you apparently also accept answers that involve modifying the PowerShell script. [`Start-Transcript`](https://learn.microsoft.com/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-6) might be easier to implement than replacing all `Write-Host` commands. Anyways, an answer that doesn't involve changing the PowerShell script is below. – iRon Jul 11 '19 at 12:55

2 Answers2

2

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
iRon
  • 20,463
  • 10
  • 53
  • 79
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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206