Suppress Write-Verbose When Calling A function in PowerShell

In a project for one of my recent Pluralsight courses, “Everyday PowerShell for Developers on Linux, macOS, and Windows“, I had created some functions in my DataFabricator module. Some of these called many child functions.

I wanted to be able to call the parent function using Verbose in order to track progress. As you may be aware though, when you call a parent function using Verbose, it carries down to all of the functions it calls. This caused a large volume of verbose messages making it difficult to find the information I wanted. Hence I needed to suppress verbose in the called functions.

Let’s see how. First let’s create two simple functions that don’t suppress verbose messages.

function Parent1()
{
  [CmdletBinding()]
  param()

  Write-Verbose "Verbose: Parent1"
  Write-Host "Parent1"
  Child1
}

function Child1()
{
  [CmdletBinding()]
  param()

  Write-Verbose "Verbose: Child1"
  Write-Host "Child1"
}

When we call the parent function with the verbose switch, we get the expected output.

Parent1 -Verbose

VERBOSE: Verbose: Parent1
Parent1
VERBOSE: Verbose: Child1
Child1

Now let’s create an alternate version of the parent function. To suppress verbose on a called child function, all that is needed is to add the verbose switch, but followed by a colon and a $false.

function Parent2()
{
  [CmdletBinding()]
  param()

  Write-Verbose "Verbose: Parent2"
  Write-Host "Parent2"
  Child1 -Verbose:$false
}

Here is the output when we call the new Parent2.

Parent2 -Verbose

VERBOSE: Verbose: Parent2
Parent2
Child1

As you can see, the verbose statements in the Child1 function do not trigger. All that was needed was to add “-Verbose:$false” as a switch when calling Child2.

And that’s all there is to it, using this simple technique you can suppress verbose messages when calling a child function, whether verbose was used to call the parent or not.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s