Using Custom Scopes to Discard Any Output

by Dec 2, 2016

Yesterday we looked at custom scopes to automatically restore variables and clean up behind your code.

Custom scopes can also be used to discard any output emitted by any part of code inside your scope. To do that, use this structure: $null = . { [code] }. Whatever you execute in the braces will run, and all variables and functions you might create will work outside of the scope, but there will not be any output.

Let’s look at this function:

function Out-Voice ($Text)
{
  $sapi = New-Object -ComObject Sapi.SpVoice
  $sapi.Speak($Text)
}

Out-Voice -Text 'Hello, Dude.'

When you run it, it makes Windows speak, but also outputs the number “1”. As it turns out, the method Speak() does this, and when you consider larger and more complex portions of code, there are many places where you’d produce data that you really don’t need.

Here is a fool-proof “diaper” function building that does the exact same, but is guaranteed to not return any value:

function Out-Voice ($Text)
{
  $null = . {
      $sapi = New-Object -ComObject Sapi.SpVoice
      $sapi.Speak($Text)
    }
}

Out-Voice -Text 'Hello, Dude.'

Twitter This Tip! ReTweet this Tip!