Is there a way to set a variable up to place output to stdout or null?

前端 未结 3 1865
北恋
北恋 2020-12-07 00:05

I would like to set up a variable in my code that would ultimately define if I\'ll see some output or not.

  • \"hello\" writes to stdout
3条回答
  •  一生所求
    2020-12-07 00:26

    Again may not be the best way, but works.

    As @Bender the Greatest has already mentioned a function with [CmdletBinding] should help the purpose.

    I'll try to provide a very basic example -

    A selective logger function like this -

    function Selective-Log {
     [CmdletBinding()]
     param(
         [Parameter()]
         [ValidateNotNullOrEmpty()]
         [string]$Message,
    
         [Parameter()]
         [ValidateNotNullOrEmpty()]
         [ValidateSet('Info','Warning','Error')]
         [string]$Severity = 'Info'
     )
    
     if($Severity -eq 'Info'){
     Write-Output $Message > $null
     }else{
     Write-Output $Message 
     }}
    

    Now when you use it in your scripts as

    Selective-Log -Message Test1 -Severity Info

    it wouldn't log anything

    Then if you wish to log you'd choose severity other than Info

    Selective-Log -Message Test2 -Severity Error

    you could also use it like Selective-Log Test2 Error

    Hope this helps someone

提交回复
热议问题