Problem
You’ve developed a useful set of functions and want to share them between multiple scripts.
Solution
First, place these common function definitions by themselves in a script, with a name that starts with Library. While the Library prefix is not required, it is a useful naming convention. Example 104 demonstrates this approach.
Example 104. A library of temperature functions
## LibraryTemperature.ps1 ## Functions that manipulate and convert temperatures
## Convert Fahrenheit to Celsius function ConvertFahrenheitToCelsius([double] $fahrenheit)
Example 104. A library of temperature functions (continued)
{ $celsius = $fahrenheit 32 $celsius = $celsius / 1.8 $celsius
}
Next, dotsource that library from any scripts that need to use those functions, as shown by Example 105.
Example 105. A script that uses a library
param([double] $fahrenheit)
$scriptDirectory = SplitPath $myInvocation.MyCommand.Path . (JoinPath $scriptDirectory LibraryTemperature.ps1)
$celsius = ConvertFahrenheitToCelsius $fahrenheit
## Output the answer "$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
Discussion
Although mostly used for libraries, you can dotsource any script or function. When you dotsource a script or function, PowerShell acts as though the calling script itself had included the commands from that script or function.