Codecademy Logo

Learn PowerShell: Functions

Functions In PowerShell

Functions are groupings of code that can be referenced elsewhere with a single call. A function consists of the following:

  • the keyword function
  • a descriptive name
  • a code body

This code snippet shows a function CustomDateTime that can be called in a script at any time to display a specific message about the current date and time.

function CustomDateTime{
$date = get-date
write-host "The current day, date, and time is:" $date
}

Benefits of Functions

Functions enhance readability, improve code integrity, and promote code reuse.

  • Readability: functions remove repetitive behaviors through code and put it in one place
  • Integrity: functions can be updated in one place and affect behaviors throughout the code
  • Reuse: functions can be used in other scripts if the same behavior is needed

Function Call

Once a function has been declared it may be called in a script via the function name. If parameters are in use, any parameters would be listed in order after the function name.

This code snippet shows two calls to a function called CountryList, which displays all countries that fit the given criteria based on the Continent and Climate values that are passed to it.

CountryList Europe Warm
CountryList Asia Cold

External Functions

Functions can be contained within a single script or referenced in separate PS1 files, provided that the external files are referenced in the main script before the function calls are made.

This code snipped shows how to use Import-Module to load functions that are in a separate file (FunctionRepository.ps1)

Import-Module .\FunctionRepository.ps1

Default Parameters

Default parameters are what the function will use anytime it runs, unless it is explicitly provided with other parameters.

This code snippet shows a function TrainStopCalculator that will display the number of stops between your pickup and destination, if you provide that information. If not, the function assumes you are going from the beginning to the end of the line.

function TrainStopCalculator{
Param($PickupStopNumber = 1, $DropoffStopNumber = 10)
$numberOfStops = $DropoffSpotNumber - $PickupSpotNumber
write-host "You have $($numberOfStops) left on your trip"
}

Learn More on Codecademy