I am using the following code to direct output to the pipeline and a log file:
"Something informative" | Tee-Object -FilePath $LogFile -Append | Write-Output
Having recently learned about the benefits of splatting, I would like to save knuckle grease by not having to retype this series of commands multiple times over. For example, I would like to assign the following portion of the command to a variable and reuse it as needed:
Tee-Object -FilePath $LogFile -Append | Write-Output
I see that you can use the call operator (&) to run commands that are stored in variables. If I store the code above into a variable and then try to call it via “Something informative” | & $Variable, I get an error message indicating that the stuff in the variable is not recognized as the name of a cmdlet or function.
Any suggestions on an efficient way to accomplish this?
There’s no reason to tack Write-Output onto the end of that pipeline, really, so just piping to Tee-Object -FilePath $LogFile -Append already shortens it quite a bit.
And you could easily make an alias - like “t” - to shorten the command name, and I think the one parameter you’re using is already positional.
When you don’t want to type something as long as te+tab we use functions. The setup can be quite arduous but the speed of entering four less characters can shave seconds off your day.
$text |Tee-Object -FilePath $logfile -Append
t -text ‘functions are your friend’ -logfile tee.txt
t ‘functions are your friend too’ tee.txt
I kid… Functions are used to do something repetitive and combined with parameters we can accept input from the command(usually a long script). write em up and save to your profile then forget you even have them.
Appreciate the input everyone.
I agree that a function would be an appropriate use of this case, but I would prefer something more simple, such as a piece of code I can define in the BEGIN block. This code would serve as a singe place to control output to both a log file and to the console.
I’ll continue looking into this and will report back when I’m able to find a solution.
You could just use Start-Transcript, and not worry about redirecting everything to the log file manually.