Thursday, March 22, 2012

Creating a Library of PowerShell Functions

If you are doing a large amount of PowerShell scripting then it is likely you have created functions that you want to reuse between scripts. You can copy and paste a function from one script to another to reuse it, but this creates maintenance issues. If you modify the function to improve it, then you need to update many scripts.

To centralize management of functions, you can create a single PowerShell script that contains all of the functions. Then you load the script containing the functions from within other scripts before you call the functions. To load the functions script, use dot sourcing like this:
. .\functions.ps1

The example above loads functions.ps1 from the same directory as the script that you ran. You can also specify a full path such as:
. C:\functions.ps1

You can also use a variable as part of the path:
. $ScriptPath\functions.ps1
Another alternative is to create multiple PowerShell scripts that you call as needed from within your script. Effectively, you would be treating each PowerShell script like it was a function. I think a single script with functions in it is more graceful.

If you create a central library of functions be sure to understand how all of the scripts use that function. A change that enhances one script may break another one.

No comments:

Post a Comment