Search code examples
powershellloggingoutputpowershell-cmdlet

PowerShell: Change default output cmdlet


Afternoon folks, I'm sorry the title is poorly written, I wasn't sure how to word it.

What I'm looking to do, if possible (without a bunch of If/Else or switch statements) is to change what cmdlet for outputting text is used. I have a logging module I've written and am working on inputting into my scripts. I'd like to however add a switch parameter to my scripts, (i.e -EnableLogging) that when called uses my logging module instead of Write-Output or Write-Host as examples.

Is this possible without doing a If/Else or Switch checking if that tag was enabled everytime I want to output to the console?

Theres not much of a code to see but:

.\script.ps1 -EnableLogging
use Write-Log (my module, instead of Write-Output)

vs

.\script.ps1
use Write-Output (instead of Write-Log)

I'm curious as to if theres a way to change/specify this besides doing this for every output

.\script.ps1 -EnableLogging

Switch($PSBoundParameters.ContainsKey('EnableLogging'){
    true {Write-Log "hello world"}
    false {Write-Output "hello world"}
}

Solution

  • If I understand correctly, this might do what you're looking for, basically you would be using | & $command on each output line, however what "command" to run is only checked once. Here is an example of what I mean:

    function Testing {
        param([switch] $EnableLogging)
    
        $command = 'Write-Output'
        if($EnableLogging.IsPresent) {
            $command = 'Write-Host'
        }
    
        'Hello World!' | & $command
        0..5 | ForEach-Object { "$_. Testing..." } | & $command
    }
    

    Now we can test if it works, if -EnableLogging is not present we should be able to capture output, in other words, Write-Output is being used, else Write-Host:

    # works, output is captured in `$tryCapture`
    $tryCapture = Testing
    # also works, output goes directly to Information Stream
    $tryCapture = Testing -EnableLogging