Conditionally write output to file for tracing pourposes

224 Views Asked by At

I have a script that accept "-outToFilename" as not mandatory parameter with the purpose,if wanted, to have a log on both console and file. Usually I'm using functions like this:

function myLogger {
    [CmdletBinding()] 
    param(
        [Parameter(Mandatory)]
        [string]$myMessage,       
        [Parameter(Mandatory)]
        [string]$logToFile
    )
    if ($logToFile) {
       write-host $myMessage |tee -append -filePath $logToFile
    } else {
       write-host $myMessage
}

But while playing with Tee-Object I was wondering whether it is possible to conditionally pipe the output of a write-host cmdlet to a tee-object
Something like this:

write-host $myMessage | if ($logToFile) { $_ | tee -filePath $logToFile }<br/>

EDIT
with tee-Object is better to use write-output so that Tee can get values from the pipeline:
write-output $myMessage | if ($logToFile) { $_ | tee -filePath $logToFile }

also, while waiting for a better solution, when I need a conditionally output to (both) console and file, I'm using this:

write-host -ForegroundColor yellow "Some text to show"
if ( $saveToFile) { Write-output  "Some text to show" | tee -FilePath $saveToFile -Append |Out-Null }
0

There are 0 best solutions below