PowerShell/Functions

From Wikiversity
Jump to navigation Jump to search

This lesson introduces PowerShell functions.

Objectives and Skills[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic function concepts.
  • Understand recursion and when to use recursive functions.
  • Create PowerShell scripts that contain and use functions.

Readings[edit | edit source]

  1. Wikipedia: Function (computer science)
  2. Wikipedia: Parameter (computer programming)
  3. Wikipedia: Recursion (computer science)
  4. BonusBits: Mastering PowerShell Chapter 9 - Functions

Multimedia[edit | edit source]

  1. YouTube: Create a Simple FUNCTION in Powershell!
  2. YouTube: PowerShell - How To - Functions

Examples[edit | edit source]

Get-Time[edit | edit source]

Get-Time is a simple function that returns a value.

# The Get-Time function returns the current time.

function Get-Time()
{
    return Get-Date -DisplayHint Time
}

Get-Time

Get-cube[edit | edit source]

Get-cube is a simple function that accepts a parameter and returns a value based on that parameter.

# The Get-cube function returns the cube (x^3) of the value provided.

function Get-cube([int]$x)
{
  $result = $x * $x * $x
  return $result
}

$x = Read-Host 'Enter a value'
$result = Get-cube $x
Write-Output "$x * $x * $x = $result"

Get-ByValue[edit | edit source]

By default, PowerShell arguments are passed by value.[1]

function Get-ByValue($value)
{
    "value = $value"
    $value = 1
    "value = $value"
}

$x = 0
Get-ByValue $x
"x = $x"  

# Output:
# value = 0
# value = 1
# x = 0

Get-ByReference[edit | edit source]

PowerShell arguments may be passed by reference using the Ref keyword.[2]

function Get-ByReference([ref]$ref)
{
    "ref = " + $ref.value
    $ref.value = 1
    "ref = " + $ref.value
}

$x = 0
Get-ByReference ([ref]$x)
"x = $x"

# Output:
# ref = 0
# ref = 1
# x = 1

Get-Args[edit | edit source]

The $args array variable may be used to access a variable length parameter list.[3]

function Get-Args()
{
    foreach($arg in $args)
    {
        $arg
    }
}

Get-Args 1 2 3 4

Get-Parameters[edit | edit source]

By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.[4]

function Show-Parameters($name, $number)
{
    "Name = $name, Number = $number"
}

Show-Parameters '1' 'Wiki'
Show-Parameters -number '1' -name 'Wiki'

# Output:
# Name = 1, Number = Wiki
# Name = Wiki, Number = 1

Show-FunctionScope[edit | edit source]

By default, variables are available only in the scope in which they are created.[5]

function Show-FunctionScope()
{
    $x = 1
    "function x = $x"
}

$x = 0
Show-FunctionScope
"script x = $x"

# Output:
# function x = 1
# script x = 0

Show-ScriptScope[edit | edit source]

You can use a scope modifier to change the scope of a variable.[6]

function Show-ScriptScope()
{
    $x = 1
    "function x = $x"
    $script:x = 2
}

$x = 0
Show-ScriptScope
"script x = $x"

# Output:
# function x = 1
# script x = 2

Get-Factorial[edit | edit source]

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.[7]

# The Get-Factorial function returns the factorial of the value provided using recursion.

function Get-Factorial([int]$value)
{
    if($value -lt 0)
    {
        $result = 0
    }
    elseif($value -le 1)
    {
        $result = 1
    }
    else
    {
        $result = $value * (Get-Factorial($value - 1))
    }
    return $result
}

$value = Read-Host 'Enter a value'
$result = Get-Factorial $value
Write-Output "$value! = $result"

Activities[edit | edit source]

  1. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and use functions to convert years to months, years to days, years to hours, and years to seconds. Avoid global variables by passing parameters to the functions and returning values from the functions. Display their approximate age in the selected timeframe.
  2. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Use functions to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Avoid global variables by passing parameters to the functions and returning values from the functions. Calculate and display the converted temperature.
  3. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Use separate functions to calculate the area of each shape and then calculate and display the area of the selected shape. Avoid global variables by passing parameters to the functions and returning values from the functions.
  4. Review MathsIsFun: Greatest Common Factor. Create a script that asks the user to enter two integer values. Based on the recursive algorithm provided in Wikipedia: Recursion (computer science), use a recursive function to calculate the greatest common factor (greatest common divisor) of the two values and then display the result.

Lesson Summary[edit | edit source]

  • A subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.[8]
  • A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the call once the subroutine's task is done.[9]
  • The content of a subroutine is its body, the piece of program code that is executed when the subroutine is called or invoked.[10]
  • A subroutine may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.[11]
  • Subroutine arguments may be passed using call-by-reference or call-by-value.[12]
  • A subroutine may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.[13]
  • A subroutine can be coded so that it may call itself recursively, at one or more places, to perform its task.[14]
  • The advantages of breaking a program into subroutines include:[15]
    • decomposing a complex programming task into simpler steps
    • reducing duplicate code within a program
    • enabling reuse of code across multiple programs
    • hiding implementation details from users of the subroutine
  • Invoking a subroutine (versus using in-line code) imposes some computational overhead in the call mechanism.[16]
  • With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).[17]
  • With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.[18]
  • Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must iterate through the list of arguments.[19]
  • Some programming languages allow subroutines to have named parameters.[20]
  • The PowerShell syntax for a declaring a function is:[21]
function name [(parameter list)] {statement list}
  • By default, PowerShell arguments are passed by value.[22]
  • PowerShell arguments may be passed by reference using the Ref keyword.[23]
  • By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.[24]
  • The $args array variable may be used to access a variable length parameter list.[25]
  • A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).[26]
  • The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.[27]
  • Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.[28]

Key Terms[edit | edit source]

call stack
A data structure that stores information about the active subroutines of a computer program.[29]
iteration
The repetition of a block of statements within a computer program.[30]
library
A collection of non-volatile resources used by programs on a computer, often to develop software.[31]
method
A subroutine associated with an object of a class that forms its interface through which other objects can access its encapsulated data.[32]
recursion
A method where the solution to a problem depends on solutions to smaller instances of the same problem.[33]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.
Click on a question to see the answer.
1. A subroutine is _____.
A subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
2. A subroutine is often coded so that it can _____, and then _____.
A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the call once the subroutine's task is done.
3. The content of a subroutine is its _____.
The content of a subroutine is its body, the piece of program code that is executed when the subroutine is called or invoked.
4. A subroutine may be written so that it expects to obtain one or more data values from the calling program _____. The calling program provides actual values for these _____, called _____.
A subroutine may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.
5. Subroutine arguments may be passed using call-by-_____ or call-by-_____.
Subroutine arguments may be passed using call-by-reference or call-by-value.
6. A subroutine may also return a computed value to its caller _____, or provide various result values or _____.
A subroutine may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.
7. A subroutine can be coded so that it may call itself _____, at one or more places, to perform its task.
A subroutine can be coded so that it may call itself recursively, at one or more places, to perform its task.
8. The advantages of breaking a program into subroutines include:
The advantages of breaking a program into subroutines include:
  • decomposing a complex programming task into simpler steps
  • reducing duplicate code within a program
  • enabling reuse of code across multiple programs
  • hiding implementation details from users of the subroutine
13. Invoking a subroutine (versus using in-line code) imposes _____.
Invoking a subroutine (versus using in-line code) imposes some computational overhead in the call mechanism.
14. With call by value, _____.
With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).
15. With call by reference, _____.
With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.
16. Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must _____.
Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must iterate through the list of arguments.
17. Some programming languages allow subroutines to have named _____.
Some programming languages allow subroutines to have named parameters.
18. By default, PowerShell arguments are passed using call by _____.
By default, PowerShell arguments are passed using call by value.
19. PowerShell arguments may be passed by reference using the _____ keyword.
PowerShell arguments may be passed by reference using the Ref keyword.
20. By default, PowerShell arguments are passed by position. _____ may be used to identify parameters, bypassing position.
By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
21. The $args array variable may be used to _____.
The $args array variable may be used to access a variable length parameter list.
22. A recursive function definition has _____, and _____.
A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).
23. The job of the recursive cases can be seen as _____. In a properly designed recursive function, with each recursive call, the input problem must be _____.
The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.
24. Recursive programming solutions include _____.
Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]

Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.