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.

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 are you using? Commented May 4, 2021 at 7:43
  • The Tee-Object cmdlet is designed for this. It passes output both to the console and to a file. Commented May 4, 2021 at 9:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.