DEV Community


Posted on • Originally published at on

Quick Tip: Checking usage of a Parameter | PowerShell

How to check if a not mandatory parameter was used on a customized PowerShell function? To answer this question, I’ve made an example where you’ll see how you can handle it.

Let’s imagine that we have the following parameters on a function…

function Set-ServiceRunningStatus{

            HelpMessage = "Enter a service name (or filter for multiple) to set Running Status")]
    BEGIN { } #BEGIN
    END { } #END  
Enter fullscreen mode Exit fullscreen mode

And we want to check if during the function execution the non-mandatory ComputerName parameter is being used… You can use the automatic variable $PSBoundParameters to perform your check.

if ($PSBoundParameters.ContainsKey('ComputerName')) {
             Write-Verbose "[PROCESS] Getting Services for $($ComputerName)"
        } else {
            Write-Verbose "[PROCESS] Getting Services"    
        }#if param ComputerName
Enter fullscreen mode Exit fullscreen mode

Let me know if it helped.

Discussion (0)