Auto-loaded Functions

Calling a loaded function from memory is more effective than calling a script file from disk. But it may be not a good idea to preload all the functions that can be potentially used if many of them actually may not be used in a session. The described technique of "auto-loaded functions" solves the dilemma: you load only what you really use and it is loaded once only on the first call.

How to use

  • Put a script into a directory included into the system path;
  • Call it from your code just by name, with no path or extension (e.g. just Encode-Xml in our example).

How it works

On the first call of Encode-Xml (with no path or extension!) from any code the script Encode-Xml.ps1 is invoked. It takes its parameters, installs the global function Encode-Xml (exactly the same name!) and calls it with all the parameters passed into the script (@PSBoundParameters). That’s it, from now on Encode-Xml calls the installed function, not the source script (function precedence is higher).

Example script with an auto-loaded function


<#
.SYNOPSIS
    Encodes literal text into XML text or attribute value.

.NOTES
    Autoloaded function.
#>

param
(
    [string]
    $Text = $(throw)
)

function global:Encode-Xml
(
    [string]
    $Text = $(throw)
)
{
    if ($args) { throw "Invalid parameters: $args" }
    $Text.Replace('&', '&amp;').Replace("'", '&apos;').Replace('"', '&quot;').Replace('<', '&lt;').Replace('>', '&gt;')
}

Encode-Xml @PSBoundParameters


See also

Organizing Your PowerShell Scripts and Functions by Joel ‘Jaykul’ Bennett

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: