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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs