1

Im new in PowerShell and working on a script more than 500 lines. I use the write-host command often. And now Im working on doing the Logging part. Also, sorry for the bad English.

I want the script to save every write-host command in a .txt, append and still let the write-host command output passthrough to the Shell output.

Things I tried:

&{
# the script 
} *>> $logPath
Start-Transcript -Path $logPath
# the script 
Stop-Transcript 

It works but its not letting the output passthrough.

german_plz
  • 11
  • 2
  • I am not able to reproduce your issue. If I replace `# the script ` with `Write-Host 'Hello World'`, it writes `Hello World` to the display. With PowerShell version and [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) are you using? – iRon May 04 '21 at 07:43
  • The `Tee-Object` cmdlet is designed for this. It passes output both to the console and to a file. – JonC May 04 '21 at 09:01

1 Answers1

1

One way of doing that would be to be to use Out-File cmdlet by wrapping your whole script like this:-

@(
Write-Output "######### Loop 1 #########"
foreach ($i in (1..5))
{
    Write-Output $i "--> Loop1"
}

Write-Output "######### Loop 2 #########"
foreach ($i in (6..11))
{
    Write-Output $i "--> Loop2"
}

Write-Output "######### Loop 3 #########"
foreach ($i in (12..15))
{
    Write-Output $i "--> Loop3"
}
) | Out-file $env:USERPROFILE\Desktop\Output.txt -width 50

Use Write-Output instead of Write-Host as Write-Host writes to the console itself where as Write-Output sends the output to the pipeline. See here for details.

Vivek Kumar Singh
  • 3,223
  • 1
  • 14
  • 27