What is the best way to deal with cmdlet log-output
It really depends on the goal of your script / cmdlet or function. In a general sense what you should do is allow for the most options and leave it up to the calling script / cmdlet or function to deal with the output. Write-Verbose
would be good if you were supporting the -Verbose
switch (and you should be). If your code already needs to use the standard output stream then you need to use at least one different one for other information. Verbose seems like a good fit but it really depends on what the information represents.
I've read that using Write-Host
is not a good idea, because it can NOT be redirected to e.g. a file.
That is no longer true with v5. Write-Host got a bad reputation for this but mostly because people misuse it. Ansgar Wiechers' answer on Write-Host vs Write-Information in PowerShell 5 does a good job giving an overview of the different streams. Write-Information
would be an obvious choice and you can redirect as you see fit. That was introduced in PowerShell v5 so you could have a portability issue there that needs to be considered.
As long as you have PowerShell v3 or higher then you could redirect verbose output to file, if you wanted to, while leaving the standard output stream alone.
# Location for verbose output
$filename = "c:\temp\verbose.txt"
# Genereate standard, verbose and error output.
$result = $("Bagel";Write-Verbose "Verbose Output"; Write-Error "Error Output") 4> $filename
# Pipeline output will be in $var
$result
# Warning output is in the file
Get-Content $filename
What's a good way to handle this problem?
To repeat: Put as much necessary output, using various streams, in your code and allow the caller to optionally enable it which also allows them to redirect or suppress on a case by case basis.