1

In the following excerpt from a function that I am working on there are 4 calls to the Tee-Object cmdlet. The first 3 write the messages to the console and the log as I wanted. The 4th one uses Write-Error and it only writes to the console.

# Run this step if the last step was successful...
if($script:BuildStepLastStatus -eq 0) {


    Write-Output $("`n" + "-"*100) | Tee-Object -FilePath  $script:BuildLogFileName -Append
    Write-Output ("[{0:yyyy-MM-dd hh:mm:ss tt}]: Step {1}..." -f (Get-Date), $StepName) | Tee-Object -FilePath  $script:BuildLogFileName -Append

    try {
        . $ScriptBlock | Tee-Object -FilePath  $script:BuildLogFileName -Append
    }
    catch {

        # Show the error details whether we will continue on error or not...
        Write-Error "$($_)`n" | Tee-Object -FilePath  $script:BuildLogFileName -Append

        if($ContinueOnError.IsPresent) {
            # 0 = success
            $script:BuildStepLastStatus = 0
        }
        else {
            # 1 = error condition
            $script:BuildStepLastStatus = 1
        }
    }
}

How can I modify this code to write errors to the console and the log?

2 Answers 2

2

AFAIK, Tee-Object accepts the contents from output stream, hence errors from error stream will be ignored. You can do the inverse.

"$($_)`n" | Tee-Object -FilePath  $script:BuildLogFileName -Append | Write-Error
Sign up to request clarification or add additional context in comments.

1 Comment

I ended using a variation on this method. I'm not sure that using Write-Error from inside a catch block is even a good idea anyway. Most example of Write-Error I see are cases where it used to cause an error to happen that will then be caught by a catch block.
1

have you looked at Redirection??

https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-5.1

https://blogs.technet.microsoft.com/heyscriptingguy/2014/03/30/understanding-streams-redirection-and-write-host-in-powershell/

2 Comments

I did look into this. It ended up not applying in this specific situation but those are both very useful references.
Just thinking you could have redirected the error stream to the output stream and then Tee'd the output stream as you'd done previously.

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.