Functions Fundamentals

Introduction to Functions

A function is a section of code that performs an action that other sections of a program can refer to. You create a function by writing code. The fundamental formula to create a function is:

function function-name {
    ...
}

The Name of a Function

Unlike traditional computer languages, the names of function in PowerShell are very flexible:

The Body of a Function

The body of a function is after the name of the function. After the parentheses, add the brackets: { and }. Here is an example:

function display {
    Write-Host 'Welcome to the wonderful world of PowerShell'
}

The section between the curly brackets is the body of the function. In that body, you can write the code that describes what the function is supposed to do.

Calling a Function

After creating a function, you can use it. Using a function is referred to as calling it. To call a simple function like the one we created above, simply type its name. Here is an example:

function display {
    Write-Host 'Welcome to the wonderful world of PowerShell'
}

display

This would produce:

PS C:\Windows\System32> C:\Exercises\Functions.ps1
Welcome to the wonderful world of PowerShell

The Scope and Lifetime of a Variable

Introduction

The scope of a variable is the extent to which it is available to other members of a project. To manage this, a variable is said to have local or global scope.

Local Variables

A variable is said to be local if it is declared in the body of a function. Here is an example:

function create {
    $middleName
}

When a variable is declared as local, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.

A Global Variable

A variable is said to be global if it is declared outside any function. Here is an example:

$strDateOfBirth

function initialize {

}

function dresent {

}

A variable that has been declared globally can be accessed by any code of the same document.

A Function that Returns a Value

Introduction

As seen in our introduction, a function has a body, which is delimited by curly brackets. Still, to indicate the end of execution of a function, type the return keyword. Here are examples:

function communicate {
    return
}
    
function take-care {
    return
}
   
function need-to-discuss {
    return
}

In this case, the return statement doesn't serve any true purpose, just to indicate the end of the function.

Returning From a Function

A function can be made to return a value. To indiate that a function returns a value, before the closing curly bracket of the function, type the return keyword followed by what to return.

Returning a Constant Value

The Primary way to return from a function is with a value. Here is an example:

function produce-number {
    return 2000
}

Returning a Variable

You can also return a variable. To do this, in the body of the function, declare a variable. If necessary, perform any operation you want. You can then assign a value or expression to the variable. Then, on the last line of the function, type return followed by the name of the variable. Here is an example:

function get-number {
    $nbr = 7483
    
    return $nbr
}

Returning an Expression

In an application, a variable is used if you are planning to use a value many times. If you need a value only once, you can use the value directly where it is needed. In the same way, if you need the returned value of a function only once, you can call the function directly where its value is needed. Here is an example:

function get-company-name {
    $companyName = 'Warrington Industries'

    return $companyName
}

function get-full-name {
    $firstName = 'Michael'
    $lastName = 'Carlock'

    return $firstName + ' ' + $lastName
}

Calling a Function that Returns Something

Storing a Function Call in a Variable

If you have a function that produces a value and you use that value more than once, you can assign the function call to a variable and then use that variable as you see fit. Here is an example:

$grossSalary = 0

function CalculateTaxAmount {
    $taxAmount = 0.00

    if( $grossSalary -lt 10000 ) {
        $taxAmount = $grossSalary * 3.00 / 100
    }
    elseif( ($grossSalary -ge 10000) -and ($grossSalary -lt 25000) ) {
        $taxAmount = 300.00 + (($grossSalary - 10000) * 4.00 / 100)
    }
    elseif (($grossSalary -ge 25000) -and ($grossSalary -lt 40000)) {
        $taxAmount = 900 + (($grossSalary - 25000) * 4.50 / 100)
    }
    elseif (($grossSalary -ge 40000) -and ($grossSalary -lt 60000)) {
        $taxAmount = 1575 + (($grossSalary - 40000) * 6.00 / 100)
    }
    else { # if ($grossSalary -ge 60000)
        $taxAmount = 2775 + (($grossSalary - 60000) * 6.50 / 100)
    }

    return $taxAmount
}

function CalculateNetPay {
    $amount = CalculateTaxAmount
    $pay    = $grossSalary - $amount

    return $pay
}

$grossSalary = 3748.85

# A function call assigned to a variable
$taxAmount   = CalculateTaxAmount
# Another function call assigned to another variable
$netPay      = CalculateNetPay

Write-Host '======================================'
Write-Host ' - Amazing DeltaX - State Income Tax -'
Write-Host '--------------------------------------'
Write-Host '          -=- West Virginia -=-'
Write-Host '======================================'
Write-Host "Gross Salary: $grossSalary"
Write-Host '--------------------------------------'
Write-Host "Tax Amount:   $taxAmount"
Write-Host "Net Pay:      $netPay"
Write-Host '======================================'

This would produce:

PS C:\Windows\System32> C:\Exercises\Functions.ps1
======================================
 - Amazing DeltaX - State Income Tax -
--------------------------------------
          -=- West Virginia -=-
======================================
Gross Salary: 3748.85
--------------------------------------
Tax Amount:   112.4655
Net Pay:      3636.3845
======================================

Calling a Function Where it is Needed

Normally, when you call a function and assign the call to a variable, you are probably planning to use the returned value many times. If you are not planning to use the returned value many times, you can call the function directly where its value is needed. In that case, type the name of the function where you want to use it and you must surround the name of the function with parentheses. Here is an example:

$grossSalary = 0

function CalculateTaxAmount {
    $taxAmount = 0.00

    if( $grossSalary -lt 10000 ) {
        $taxAmount = $grossSalary * 3.00 / 100
    }
    elseif( ($grossSalary -ge 10000) -and ($grossSalary -lt 25000) ) {
        $taxAmount = 300.00 + (($grossSalary - 10000) * 4.00 / 100)
    }
    elseif (($grossSalary -ge 25000) -and ($grossSalary -lt 40000)) {
        $taxAmount = 900 + (($grossSalary - 25000) * 4.50 / 100)
    }
    elseif (($grossSalary -ge 40000) -and ($grossSalary -lt 60000)) {
        $taxAmount = 1575 + (($grossSalary - 40000) * 6.00 / 100)
    }
    else { # if ($grossSalary -ge 60000)
        $taxAmount = 2775 + (($grossSalary - 60000) * 6.50 / 100)
    }

    return $taxAmount
}

function CalculateNetPay {
    $amount = CalculateTaxAmount
    $pay    = $grossSalary - $amount

    return $pay
}

$grossSalary = 18755.50

Write-Host '======================================'
Write-Host ' - Amazing DeltaX - State Income Tax -'
Write-Host '--------------------------------------'
Write-Host '          -=- West Virginia -=-'
Write-Host '======================================'
Write-Host "Gross Salary:  $grossSalary"
Write-Host '--------------------------------------'
Write-Host "Tax Amount:   " (CalculateTaxAmount)
Write-Host "Net Pay:      " (CalculateNetPay)
Write-Host '======================================'

This would produce:

PS C:\Windows\System32> C:\Exercises\Functions.ps1
======================================
 - Amazing DeltaX - State Income Tax -
--------------------------------------
          -=- West Virginia -=-
======================================
Gross Salary:  18755.5
--------------------------------------
Tax Amount:    650.22
Net Pay:       18105.28
======================================

Primary options of Functions

Conditionally Returning a Value

When performing its assignment, a function can encounter different situations. You can make the function produce a result that depends on some condition.

We are already familiar with the ability for a function to return a value. In some cases, the value you want to return is not a simple constant: It may depend on some condition. To make this happen, you have various options. One function is to create one or a series of conditional statements in a function. Each condition would return a value of your choice. The rule is that, by the end of the function, every possible value must have been returned. Here is an example of such a function:

$grossSalary

function CalculateTaxAmount {
    if ($grossSalary -lt 10000) {
        return grossSalary * 3.00 / 100
    }
    elseif( ($grossSalary -ge 10000) -and ($grossSalary -lt 25000) ) {
        return 300.00 + (($grossSalary - 10000) * 4.00 / 100)
    }
    elseif( ($grossSalary -ge 25000) -and ($grossSalary -lt 40000)) {
        return 900 + (($grossSalary - 25000) * 4.50 / 100)
    }
    elseif( ($grossSalary -ge 40000) -and ($grossSalary -lt 60000)) {
        return (($grossSalary - 40000) * 6.00 / 100)
    }
    else { # if ($grossSalary -ge 60000)
        return 2775 + (($grossSalary - 60000) * 6.50 / 100)
    }
}

$grossSalary = 117635

$amount = CalculateTaxAmount
$netPay  = $grossSalary - $amount

Write-Host '============================================'
Write-Host ' - Amazing DeltaX - State Income Tax -'
Write-Host '--------------------------------------------'
Write-Host '          -=- West Virginia -=-'
Write-Host '============================================'
Write-Host "Gross Salary:  $grossSalary"
Write-Host '--------------------------------------------'
Write-Host "Tax Amount:   " $amount
Write-Host "Net Pay:      " $netPay
Write-Host '============================================'

This would produce:

PS C:\Windows\System32> C:\Exercise09\Functions.ps1
============================================
 - Amazing DeltaX - State Income Tax -
--------------------------------------------
          -=- West Virginia -=-
============================================
Gross Salary: 117635
--------------------------------------------
Tax Amount:    6521.275
Net Pay:       111113.725
============================================

Exiting Early From a Function

One of the goals of a condition statement is to check a condition in order to reach a conclusion. One of the goals of a function is to perform an action if a certain condition is met. In fact, by including a condition in a function, you can decide whether the action of a function is worth pursuing or completing. In the body of a function where you are checking a condition, once you find out that a certain condition is not met, you can stop checking the condition and get out of the function. This is done with the return keyword. To apply it, in the body of a conditional statement in a function, once you decide that the condition reaches the wrong outcome, type return (and an optional semicolon).

Nesting a Function

As mentioned in our introduction, a function is a section of code that solves a specific problem. Sometimes, you will find out that a function you had created is useful to only one other function. This means that, in this case, only a certain function A calls a certain function B and no other function calls that function B. If you have a section of code that only a certain function calls, you can create a function for that section in the body of the unique function that calls it.

A local function is a function that is created in the body of another function. A function created inside another function is also referred to as nested. After creating a nested function, call it by its name as we have done for the others. Here is an example of creating and calling a nested function:

$grossSalary = 4017.96

function CalculateTaxAmount {
    if($grossSalary -lt 10000) {
        return $grossSalary * 3.00 / 100
    }
    elseif( ($grossSalary -ge 10000) -and ($grossSalary -lt 25000) ) {
        return 300.00 + (($grossSalary - 10000) * 4.00 / 100)
    }
    elseif( ($grossSalary -ge 25000) -and ($grossSalary -lt 40000) ) {
        return 900 + (($grossSalary - 25000) * 4.50 / 100)
    }
    elseif( ($grossSalary -ge 40000) -and ($grossSalary -lt 60000) ) {
        return (($grossSalary - 40000) * 6.00 / 100)
    }
    else { # if ($grossSalary -ge 60000)
        return 2775 + (($grossSalary - 60000) * 6.50 / 100)
    }
}

function CalculateNetPay {
    $amt = CalculateTaxAmount
    return $grossSalary - $amt
}

function Present {
    Write-Host "============================================"
    Write-Host " - Amazing DeltaX - State Income Tax -"
    Write-Host "--------------------------------------------"
    Write-Host "          -=- West Virginia -=-"
    Write-Host "============================================"

    # Nesting a function
    function display {
        Write-Host "Gross Salary: $grossSalary"
        Write-Host "--------------------------------------------"
        Write-Host "Tax Amount:   " (CalculateTaxAmount)
        Write-Host "Net Pay:      " (CalculateNetPay)
        Write-Host "============================================"
    }

    # Calling a nested function
    display
}

# Calling a function
Present

This would produce:

PS C:\Windows\System32> C:\Exercise09\Functions.ps1
============================================
 - Amazing DeltaX - State Income Tax -
--------------------------------------------
          -=- West Virginia -=-
============================================
Gross Salary: 4017.96
--------------------------------------------
Tax Amount:    120.53880000000001
Net Pay:       3897.4212
============================================

Previous Copyright © 2001-2025, FunctionX Tuesday 11 February 2025, 16:07 Next