PowerShell/Functions
This lesson introduces PowerShell functions.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editGet-Time
editGet-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
editGet-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
editBy 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
editPowerShell 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
editThe $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
editBy 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
editBy 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
editYou 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
editThe 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- 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
edit- 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- 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- 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
editSee Also
editReferences
edit- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Ref
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Variables
- ↑ Microsoft TechNet: about_Variables
- ↑ Wikipedia: Factorial
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Ref
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Functions
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Call stack
- ↑ Wikipedia: Iteration
- ↑ Wikipedia: Library (computing)
- ↑ Wikipedia: Method (computer programming)
- ↑ Wikipedia: Recursion (computer science)