PowerShell: How to pass multiple parameters into a function in PowerShell

No comments

In this post I will show how to pass multiple parameters into a function in PowerShell coding.

 Addition of numbers function using PowerShell example:

cls
#The below sample function will accept numeric paramters and do the addtion.
Function Add-Numbers()
{
    
    param
    (
        [Parameter(Mandatory=$true)] [int32] $FirstNumber,
        [Parameter(Mandatory=$true)] [int32] $SecondNumber,
        [Parameter(Mandatory=$false)][int32] $ThirdNumber
       
    )
 
    Try 
    {

        
        $resultNumber=$FirstNumber+$SecondNumber+$ThirdNumber;

        
        Write-host -f Green "Addition of" $FirstNumber, $SecondNumber "and" $ThirdNumber "is: " $resultNumber
    }
    Catch 
    {
            
            $ErrorMessage = $_.Exception.Message +"while doing the addition"
            Write-Host $ErrorMessage -BackgroundColor Red
            


    }
    return $resultNumber;
}

#Parameters - how to pass parameter to the function:
$firstNumber=10;
$secondNumber=10;
$thirdNumber=10;
Add-Numbers $firstNumber $secondNumber $thirdNumber
#Parameters ends

Test the addition of numbers function script:

PowerShellFunctionWithParametersExample

Summary:

Hence, in this post we have learned the below concepts of PowerShell:

  • How to make a parameter mandatory in PowerShell
  • How to make a parameter optional in PowerShell
  • What are parameters in PowerShell?
  • How to add multiple parameter sets to a PowerShell function
  • How to use Parameters in PowerShell
  • Getting input into PowerShell Functions with Parameters
  • Number (int32) datatype in PowerShell.
  • The parameters,data types,return value in PowerShell function.