I currently have a script that is executed as follows:
.\script.ps1 “param1” “param2” 2>&1 | tee -filePath buildlog.txt
I can’t find a way to do the following.. logging to both the console and file encapsulated within the script.
.\script.ps1 “param1” “param2”
Here’s my attempt at doing it:
powershelltest.ps1
param([string]$paramOne, [string]$paramTwo)
function DoWork()
{
Write-Host '3'
}
function WriteLogFile()
{
DoWork
# The following would not be captured by Start-Transcript & Stop-Transcript
# program.exe ....
Write-Host '4'
}
function CollectorFunction()
{
Write-Host '2'
WriteLogFile;
Write-Host '5'
}
Write-Host '1'
CollectorFunction 2>&1 | tee -filePath c:\log.foo
If you want to write to a log file don’t use
Write-Host. UseWrite-Outputor don’t useWrite-*at all becauseWrite-Outputis the default e.g:is equivalent to:
Write-Outputsends output to the stdout stream (ie 1). UseWrite-Errorto send output to the error stream (ie 2). These two streams can be redirected.Write-Hostmore or less writes directly to the host UI bypassing output streams altogether.In PowerShell V3, you can also redirect the following streams: