PowerShell functions parameters with Example

In this article, I’ll explain to you what are PowerShell functions parameters and how you can pass the parameter to a PowerShell function.

So let’s start creating a PowerShell function and pass parameters to that function.

 

PowerShell functions parameters

PowerShell functions parameters

In PowerShell, you can define function parameters to accept input values when the function is called. Functions parameters are defined using the “Param” keyword followed by a list of parameters in parentheses.

Functions parameters with Param

 

Function Get-Greeting {

Param(

[string]$Name

)

return "Hello, $Name!"

}

$msg  = Get-HelloMessage -Name "geekstutorials.com"
Write-Host $msg

 

The use of the “Param” keyword for parameters is not mandatory the parameters also work without the param keyword as well see the below example –

Functions parameters without Param

Function Get-HelloMessage([string]$Name) {

return "Hello, $Name!"

}

$msg = Get-HelloMessage -Name "geekstutorials.com"

Write-Host $msg

 

The Get-HelloMessage function has a single input parameter called $Name. This parameter is defined as a string, which means it can only accept string values.

I have called the Get-HelloMessage function and passed the parameter value “geekstutorials.com” to it. The function returned the output “Hello geekstutorials.com” and this value was assigned to the variable $msg and printed the same on the console using the write-host command.

The above example has only one parameter you can also define functions with multiple parameters.

Example –

Function Get-Sum([int]$Num1, [int]$Num2) {

$Sum = $Num1 + $Num2

return $Sum

}

In this example, the Get-Sum function has two input parameters: $Num1 and $Num2. Both parameters are defined as integers, which means they can only accept integer values.

 

To call this function and pass in values for both parameters, you can use the following syntax:

$Result = Get-Sum -Num1 100 -Num2 150

This would assign the value 250 to the $Result variable. Below is the Output –

Function Get-Sum([int]$Num1, [int]$Num2) {

$Sum = $Num1 + $Num2

return $Sum

}

$Result = Get-Sum -Num1 100 -Num2 150

Write-Host $Result

Output –

powershell functions parameters output

Note – The “testps.ps1”  have the above script I have run the same using the PowerShell editor.

Conclusion

This is how you can use PowerShell functions parameters to take input values when the function is called. The use of the “Param” keyword is not mandatory the function parameter can be defined with or without param. I hope now you have some insights into how PowerShell function parameters work.