CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Functions

Functions are code blocks holds the sequence of statements and can be called using their names whenever / wherever required. The list of statements inside the function are grouped with in the curly braces (“{ }”).

Defining and using the Functions in PowerShell are easy and will discuss how to do this in this Article.

Defining a Function

In PowerShell, functions are defined using the keyword function, following the function name. Statements with in the function are grouped inside the curly braces (“{ and }”). And each statement should be either separated by a semicolon (“;”) or separated by a new line. Here is the syntax of the function:

function Function-Name
{
    Statement-1
    Statement-2 
}

You can given any name to the function. The name should not be a PowerShell keyword. It is recommended to follow naming rules to name the functions in PowerShell. For example, if your function purpose is to list top 10 processes which are consuming more CPU usage; name the function as List-ProcessesTop10 or some other meaningful name.

Passing Arguments to the Function

Functions can take arguments. Arguments are optional. To define the arguments; you must use param keyword, if you want define them inside the function body. You can define the arguments without param keyword, if you want to define them out side the function body. Parameters are separated by a comma (“,”).

Here are the examples:

Parameters defined within the function body.

function Function-Name
{
    param($arg1, $arg2)
    
    Statement-1
    Statement-2
}

Outside defined parameters.

function Function-Name
($arg1, $arg2)
{
    Statement-1
    Statement-2
}

Calling Functions

We can call the PowerShell function by it’s name. If any arguments are defined, we can pass their values when calling the function; argument name followed by space and then the value of the argument. Parameter name must be prefixed with hyphen (“-“).

PS C:\> function Test-Function ($Name, $Value) {
>> echo $Name
>> echo $Value
>> }
>>
PS C:\> Test-Function -Name "David" -Value 28
David
28
PS C:\>

Remember that, if you are passing the arguments with name are called named arguments. You can pass the argument values, without their name too; but you need to remember the order of the arguments.

PS C:\> Test-Function David 28
David
28

We will discuss more topics in my upcoming articles.

[..] David

PowerShell – Functions

One thought on “PowerShell – Functions

Leave a Reply

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

Scroll to top