1

I distilled this from a larger script. The problem I'm having is that the out-file doesn't work to save "sdfsdfad" to a file and instead prints to the console "sdfsdfad".

    $ErrorActionPrefence   = "Stop"

    $s1=@'
        for($i=0; $i -lt 10; $i++) {
            write-host "sdfsdfad"
        }

    '@

    $s1 > $env:userprofile\Documents\s1.ps1

    $sb = {
        $ErrorActionPreference   = "Stop"

        Set-PSDebug -Trace 0
    
        $alog = "$env:userprofile\Documents\a2.txt"
    
        $null > $alog    

        invoke-expression $env:userprofile\Documents\s1.ps1 | out-file -Append $alog
    }

    start-job -ScriptBlock $sb | Receive-job -wait

    Get-Content $env:userprofile\Documents\a2.txt

Console Output that is suppose to be in "~\Documents\a2.txt" instead:

sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
sdfsdfad
pico
  • 1,660
  • 4
  • 22
  • 52
  • 1
    `Write-Host` goes to the `Information Stream`. Redirect it to stdout if you want to capture it's output `6>&1 | Out-File ...` – Santiago Squarzon Nov 04 '21 at 19:56
  • 1
    Does this answer your question? [PowerShell Capture Write-Host output](https://stackoverflow.com/questions/50937190/powershell-capture-write-host-output) – Santiago Squarzon Nov 04 '21 at 19:58

1 Answers1

2

In cases where you don't have control over a script that uses Write-Host, you can use 6>&1 to redirect that output to the success output stream in order to send it through the pipeline, so that Out-File saves it.
Note that this only works in PowerShell v5 and above.

See this answer for more information about capturing Write-Host output, and this answer for information about redirection syntax such as 6>&1.

Applied to your code (if you really must stick with Write-Host):

& $env:userprofile\Documents\s1.ps1 6>&1 | out-file -Append $alog

Or, more simply, given that >> is effectively an alias of Out-File -Append:

& $env:userprofile\Documents\s1.ps1 6>&1 >> $alog

Note:

  • Unlike in POSIX-compatible shells such as bash, the order of the redirections does not matter.
  • You can merge multiple streams selectively into the success output stream, or simply target all streams (see below).

Or, even simpler, to catch all (*) output streams:

& $env:userprofile\Documents\s1.ps1 *>> $alog
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    I guess my bad on voting for closure due to duplicate answer, tho I do feel OP is hardly listening to the advice we're giving hehe – Santiago Squarzon Nov 04 '21 at 20:05
  • 2
    @SantiagoSquarzon, closing it as a duplicate would definitely have been an option. However, I wanted to call out the anti-patterns in the question explicitly (not least because the OP has misused `Invoke-Expression` before, at which time I only called it out in a comment, which was ignored). – mklement0 Nov 04 '21 at 20:10