Search code examples
powershellnulloutputvoid

How to suppress all the output except explicit Write-Host


How to suppress all the uninvited output? I recently started coding on PS and this obsessive ubiquitous output everywhere drives me crazy. I have to spam | Out-Null, [void] all around the codebase keeping an eye on every call because otherwise, the function will return a corrupted value with a bunch of parasite neighbors. Like a developer mainly on traditional languages, I don't understand the pleasure of seeing in the terminal a whole bunch of bullshit like 0, 7582645, ============ etc. Ideally, I want that output will fires only when I explicitly ask it for - echo/print/Write-Host and nothing more. I've tried some workarounds but with no luck. A tiny synthetic example:

function out-default
{
    $input | out-null
}
$PSDefaultParameterValues = @{
    'New-Item:OutVariable' = 'Null'
    'Disabled' = $False
}

function get
{
    "1"
    [Text.Encoding]::ASCII.GetBytes( "test" )
    return "value"
}

get

<#
the output actual: 1 116 101 115 116 value
the output wanted: value
#>

Anybody save me, please :(


Solution

  • I actually answered this question here: https://stackoverflow.com/a/75542335/4891401

    TL;DR (but also too long)

    If you just type the variable 'freely', then it will output the value, just like if you had put Write-Host in front of it.

    Example:

    $a = "Hello"
    $a
    
    # output: Hello
    

    If you don't want to output $a, then using the example above:

    $a = "Hello"
    
    # output: 
    

    A few points about your question; we cannot see important code to distinguish what is happening in your script, e.g. What is the value of $input? Also, all of the commands you are running are not being assigned to anything, so obviously, it will output it's return value into the terminal. Below is an attempt to remove this from your code,

    function out-default
    {
        
    }
    $PSDefaultParameterValues = @{
        'New-Item:OutVariable' = 'Null'
        'Disabled' = $False
    }
    
    function get
    {
        return "value"
    }
    
    get
    
    # output: value
    

    An alternative way of fixing could be:

    <#function out-default
    {
        $input | out-null
    }#>
    $PSDefaultParameterValues = @{
        'New-Item:OutVariable' = 'Null'
        'Disabled' = $False
    }
    
    function get
    {
        $variable1 = "1"
        $encodingtest = [Text.Encoding]::ASCII.GetBytes( "test" )
        return "value"
    }
    
    get
    
    # output: value
    

    In this example I have decided to comment out the first function as it serves no purpose to the script, as you are only calling the get function and never calling out-default function