0

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 }
  • You would need to place the condition before the `Write-Host`. You cannot pipe something to an `if` statement. ;-) – Olaf Apr 10 '20 at 08:38
  • 2
    from what i can tell, the `Write-Host` cmdlet does not output ANYTHING to the output stream - and thus nothing for a pipe to send onward. no `-PassThru`, no `-OutVariable`, no `-PipelineVariable` ... _nothing_. [*grin*] – Lee_Dailey Apr 10 '20 at 09:00
  • BTW: You wouldn't actually need a `Write-Host` to output something to the console AND to a file with `Tee-Object`. Just *call* your variable `$myMessage` as it is and pipe that to `Tee-Object` ;-) – Olaf Apr 10 '20 at 09:30
  • @Olaf yes, actually I'm doing this "if statement" thing **if {$file) {write-output $msg | tee -filepath $file} else {write-host $message}** but I don't like to duplicate code, specially when $message is a string that changes many time. – pink0.pallino Apr 10 '20 at 16:12
  • @Lee_Dailey yep, You are right, I discovered that tight after posting the message. I'm using **write-output** for the **Tee-Object** and **write-host** for standard output – pink0.pallino Apr 10 '20 at 16:17
  • My previous searches pointed to [https://stackoverflow.com/questions/30694007/conditionally-piping-to-out-null](https://stackoverflow.com/questions/30694007/conditionally-piping-to-out-null) but I'm not able to replace **out-Null** with **out-file -path $path** or whatever command – pink0.pallino Apr 10 '20 at 16:20
  • @pink0.pallino - kool! glad to know that you found a fix ... [*grin*] – Lee_Dailey Apr 10 '20 at 22:33
  • @pink0.pallino ... but your question shows another code snippet. You might update your question with the code you're actually using. ;-) – Olaf Apr 10 '20 at 23:04

0 Answers0