Verbose Parameter Passing to cmdlet inside Function

Well, almost all powershell cmdlets, functions and workflows have a Verbose parameter that displays more information about what the command is doing during it's execution. But how are we going to take advantage of this parameter when building our own functions and scripts?

First of all, we have to include the "cmdletBinding()] statement. This will add the -Verbose switch to the function/script and when we call the function with that script the output from the command "Write-Verbose" will be displayed.

Take the following function for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Function Test
{
    [cmdletBinding()]

    Param
    (
    )

    Write-Verbose "Started"

    Start-Sleep -Seconds 5

    Write-Verbose "Completed."
}

All it does is sleep for five seconds. If we call it without the -Verbose switch it will display nothing. With the -Verbose switch it will display the "Started" message before sleeping and "Completed" afterwards.

Please not that when you use "[cmdletBinding()]", the "Param()" statement has to follow even if there are no other parameters.

Now, let's go a bit deeper. What if we've built a function that uses other cmdlets that support the -Verbose switch. How are we going to pass that switch to those cmdlets? That's easy, when we call the inner cmdlet, let's say Remove-Item, we use the following format:

1
Remove-Item -Verbose:($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent -eq $true) 

We check if the Verbose switch can be found in the parameters that have been specified when our custom function was invoked and we pass that value to the cmdlet's Verbose value.

Popular posts from this blog

Domain Controller Machine Password Reset

Configuring a Certificate on Exchange Receive Connector

Running Multiple NGINX Ingress Controllers in AKS