Functions
In PowerShellFunctions are groupings of code that can be referenced elsewhere with a single call. A function consists of the following:
function
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-datewrite-host "The current day, date, and time is:" $date}
Functions
Functions enhance readability, improve code integrity, and promote code reuse.
Function
CallOnce 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 WarmCountryList 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 - $PickupSpotNumberwrite-host "You have $($numberOfStops) left on your trip"}