Archive for October, 2009

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

    Encodes literal text into XML text or attribute value.

    Autoloaded function.

    $Text = $(throw)

function global:Encode-Xml
    $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

Leave a comment