german_plz
german_plz

Reputation: 11

PowerShell Write-Host append to a text file

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.

Upvotes: 1

Views: 1717

Answers (1)

Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

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.

Upvotes: 1

Related Questions