Pass Multiple Parameters into a Function in PowerShell

Once you start advanced topics in PowerShell you will come across this scenario where you need to Pass Multiple Parameters into a Function in PowerShell.

There are simple and complex ways of defining parameters in PowerShell. Both ways will have their own benefits. Often while writing the PowerShell script or a function we need to pass either filename, strings as a parameter to the function or script.

Pass Multiple Parameters into a Function in PowerShell

#1. Use the Datatype in the Function Arguments

The first approach is to pass strict data type into the function arguments. Using the data types is always helpful as if there is any mismatch it will throw an error and stop running the script. Here is the example of passing multiple parameters to the functions and note the data type used is a string.

function PrintValues([string]$arg1, [string]$arg2)
{
    Write-Host "`$arg1 value: $arg1"
    Write-Host "`$arg2 value: $arg2"
}

In order to execute the function refer to the screenshot attached below. Just call the function name and pass the parameters as a string next to it. If you have multiple parameters then use space to differentiate between them.

Pass Multiple Parameters Into A Function In Powershell

#2. Function Arguments without Datatype

The second approach is just declaring the parameters in the function. We have not given any data type to it. Hence you could pass any data type like string, int, bool etc. This is not the recommended approach unless you know what exactly is gonna happen if a wrong data type is passed to it.

Below is the example of Passing multiple parameters to the PowerShell function without any datatype.

function addition($a, $b, $c) {
   $sum =$a +$b+$c
   Write-Host "Sum of 3 numbers is"
   $sum
}

Executing the function and Output of the function

PS C:\Users> function addition($a, $b, $c) {
>>    $sum =$a +$b+$c
>>    Write-Host "Sum of 3 numbers is"
>>    $sum
>> }
# PS C:\Users> addition 1 2 3
# Sum of 3 numbers is
# 6
# PS C:\Users>
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like