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

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

No comments

 23,253 total views,  4 views today

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 parameters 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 the 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.

See Also:

 

Free download SharePoint Online & Office 365 Administration eBook(238 Pages)

Get the PDF eBook from here:


[purchase_link id="0" style="button" color="blue" text="Free Download SharePoint Online & Office 365 Administration"]

 

 
FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.