PowerShell – Call Function with Parameters

Call Function with Parameters in PowerShell

Using Positional Parameters

To call a function, use positional parameters separated by space. Please note that you need to pass parameters in sequence while calling the function.

Microsoft’s PowerShell consists of a command-line shell and scripting language. It is based on the .NET framework for task automation and configuration management and helps power users and IT specialists in automating and controlling Windows-based systems. We can manage computers from the command line.

A function is a code block that organizes and reuses code by taking parameters as input and returning values as output. PowerShell’s definition requires the function keyword, then the function’s name, and a series of parentheses that could include parameter values.

Functions are similar to cmdlets; the core difference is that functions are implemented as script blocks and can be used in any .NET language, while cmdlets’ implementation uses .NET classes for use with the PowerShell runtime. So, for example, we created a function getEmployee that accepts name, age, and salary as parameters.

In PowerShell, we can use positional parameters to call a function by specifying the values for the parameters in the order of their definition in the function. Positional parameters can be helpful if we are familiar with the order of the parameters and want to avoid specifying the parameter names. For example, to call the function getEmployee using positional parameters, you specified the values for the name, age, and salary parameters in the order they are defined in the function.

Using Named Parameters

To call a function, use order-independent named parameters.

We discussed PowerShell and function while discussing calling the function with positional parameters. In this section, we used order-independent named parameters to call a function.

In PowerShell, named parameters allow us to specify the values for function parameters by name rather than by position. They make the code more self-explanatory and easier to understand the purpose of each parameter, as the names describe their function. For example, we used named parameters -salary, -name, and -age to call the function getEmployee to make it clear which value goes with which parameter.

That’s all about how to call function with parameters in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *