# PowerShell/Functions

This lesson introduces PowerShell functions.

## Objectives and Skills

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

* Wikipedia: Function (computer science)
* Wikipedia: Parameter (computer programming)
* Wikipedia: Recursion (computer science)
* BonusBits: Mastering PowerShell Chapter 9 - Functions

## Multimedia

* YouTube: Create a Simple FUNCTION in Powershell!
* YouTube: PowerShell - How To - Functions

## Examples
#### Get-Time

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

#### Get-cube

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

#### Get-ByValue

By default, PowerShell arguments are passed by value.

#### Get-ByReference

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

#### Get-Args

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

#### Get-Parameters

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

#### Show-FunctionScope

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

#### Show-ScriptScope

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

#### Get-Factorial

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

## Activities

* 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.
* 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.
* 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.
* 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

* A subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
* 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.
* The content of a subroutine is its body, the piece of program code that is executed when the subroutine is called or invoked.
* 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.
* Subroutine arguments may be passed using call-by-reference or call-by-value.
* A subroutine may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.
* A subroutine can be coded so that it may call itself recursively, at one or more places, to perform its task.
* 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
* Invoking a subroutine (versus using in-line code) imposes some computational overhead in the call mechanism.
* 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).
* With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.
* 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.
* Some programming languages allow subroutines to have named parameters.
* The PowerShell syntax for a declaring a function is:
* By default, PowerShell arguments are passed by value.
* PowerShell arguments may be passed by reference using the Ref keyword.
* By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
* The $args array variable may be used to access a variable length parameter list.
* 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).
* 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.
* Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.

## Key Terms
### call stack

    A data structure that stores information about the active subroutines of a computer program.

### iteration

    The repetition of a block of statements within a computer program.

### library

    A collection of non-volatile resources used by programs on a computer, often to develop software.

### method

    A subroutine associated with an object of a class that forms its interface through which other objects can access its encapsulated data.

### recursion

    A method where the solution to a problem depends on solutions to smaller instances of the same problem.

## Review Questions

* 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

## Assessments

* Flashcards: Quizlet: Windows PowerShell - Functions
* Quiz: Quizlet: Windows PowerShell - Functions