fbpx Place Common Functions in a Library in Windows PowerShell | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Place Common Functions in a Library in Windows PowerShell

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.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Processor Intel Atom C2350 1.7 GHz 2c/2t RAM 4 GB DDR3 Storage 1× 1 TB (HDD SATA) Server Detail Configure Server
Processor Intel Atom C2350 1.7 GHz 2c/2t RAM 4 GB DDR3 Storage 1× 128 GB (SSD SATA) Server Detail Configure Server
Processor Intel Atom C2750 2.4 GHz 8c/8t RAM 8 GB DDR3 Storage 1× 1 TB (HDD SATA) Server Detail Configure Server
Processor Intel Xeon E3-1230 v2 3.3 GHz 4c/8t RAM 16 GB DDR3 Storage 1× 256 GB (SSD SATA) Server Detail Configure Server
Processor Intel Atom C2350 1.7 GHz 2c/2t RAM 4 GB DDR3 Storage 1× 250 GB (SSD SATA) Server Detail Configure Server

What Our Clients Say