DEV Community

ToolGBRMaker
ToolGBRMaker

Posted on • Originally published at toolgbrmaker.wordpress.com 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{
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$true)]

        [string[]]$ComputerName,
        [Parameter(Mandatory=$true,
            HelpMessage = "Enter a service name (or filter for multiple) to set Running Status")]
        [string]$Name,
        [switch]$Force
    )
    BEGIN { } #BEGIN
    PROCESS { } #PROCESS
    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.

Top comments (0)