PoshCode Logo PowerShell Code Repository

Autoload Module 1.2 by Travis 5 years ago (modification of post by Joel Bennett view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/3265"></script>download | new post

Autoload function like the Korn shell — can inject functions to modules.

In order to make this easier to use, I’ve added the ability to run AutoLoad against script files (that don’t have a function in them). It will ultimately create a function out of the script.

The main purpose of this module is to allow defining functions in a script file without needing to dot-source the script in order to use them. You simply autoload that function, and there’s little overhead until the function is called (at which time it’s parsed and loaded, once). This way, autoload helps you avoid loading functions into memory until you need them — but allows you to write code as though the functions were already loaded.

Note: The Functions/Scripts are only actually parsed the first time you call the function (or when you call Get-AutoloadHelp on the function). You should be aware of that when making changes to the script.

  1. #Requires -Version 2.0
  2. ## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
  3. ## Provides significant memory benefits over pre-loading all your functions, and significant performance benefits over using plain scripts.  Can also *inject* functions into Modules so they inherit the module scope instead of the current local scope.
  4. ## Please see the use example in the script below
  5.  
  6. ## Version History
  7. ## v 1.2  - 2011.05.02
  8. ##        - Exposed the LoadNow alias and the Resolve-Autoloaded function
  9. ## v 1.1  - 2011.02.09
  10. ##          Added support for autoloading scripts (files that don't have a "function" in them)
  11. ## v 1.0  - 2010.10.20
  12. ##          Officially out of beta -- this is working for me without problems on a daily basis.
  13. ##          Renamed functions to respect the Verb-Noun expectations, and added Export-ModuleMember
  14. ## beta 8 - 2010.09.20
  15. ##          Finally fixed the problem with aliases that point at Invoke-Autoloaded functions!
  16. ## beta 7 - 2010.06.03
  17. ##          Added some help, and a function to force loading "now"
  18. ##          Added a function to load AND show the help...
  19. ## beta 6 - 2010.05.18
  20. ##          Fixed a bug in output when multiple outputs happen in the END block
  21. ## beta 5 - 2010.05.10
  22. ##          Fixed non-pipeline use using $MyInvocation.ExpectingInput
  23. ## beta 4 - 2010.05.10
  24. ##          I made a few tweaks and bug fixes while testing it's use with PowerBoots.
  25. ## beta 3 - 2010.05.10
  26. ##          fix for signed scripts (strip signature)
  27. ## beta 2 - 2010.05.09
  28. ##          implement module support
  29. ## beta 1 - 2010.04.14
  30. ##          Initial Release
  31.  
  32.  
  33. ## To use:
  34. ## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
  35. ## For example:
  36. <#
  37. function Skip-Object {
  38. param(
  39.    [int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,  
  40.    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
  41.    $InputObject
  42. )
  43. begin {
  44.    if($Last) {
  45.       $Queue = new-object System.Collections.Queue $Last
  46.    }
  47.    $e = $every; $UpTo++; $u = 0
  48. }
  49. process {
  50.    $InputObject | where { --$First -lt 0 } |
  51.    foreach {
  52.       if($Last) {
  53.          $Queue.EnQueue($_)
  54.          if($Queue.Count -gt $Last) { $Queue.DeQueue() }
  55.       } else { $_ }
  56.    } |
  57.    foreach {
  58.       if(!$UpTo) { $_ } elseif( --$u -le 0) {  $_; $U = $UpTo }
  59.    } |
  60.    foreach {
  61.       if($every -and (--$e -le 0)) {  $e = $every  } else { $_ }
  62.    }
  63. }
  64. }
  65. #>
  66.  
  67. ## 2) Put the function into a script (for our example: C:\Users\${Env:UserName}\Documents\WindowsPowerShell\Scripts\SkipObject.ps1 )
  68. ## 3) Import the Autoload Module
  69. ## 5) Run this command (or add it to your profile):
  70. <#
  71. New-Autoload C:\Users\${Env:UserName}\Documents\WindowsPowerShell\Scripts\SkipObject.ps1 Skip-Object
  72. #>
  73.  
  74. ## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
  75. ## Now, you can just use the function:
  76. ## 1..10 | Skip-Object -first 2 -upto 2
  77.  
  78. function Invoke-Autoloaded {
  79. #.Synopsis
  80. #       This function was autoloaded, but it has not been parsed yet.
  81. #  Use Get-AutoloadHelp to force parsing and get the correct help (or just invoke the function once).
  82. #.Description
  83. #   You are seeing this help because the command you typed was imported via the New-Autoload command from the Autoload module.  The script file containing the function has not been loaded nor parsed yet. In order to see the correct help for your function we will need to parse the full script file, to force that at this time you may use the Get-AutoloadHelp function.
  84. #
  85. #   For example, if your command was Get-PerformanceHistory, you can force loading the help for it by running the command: Get-AutoloadHelp Get-PerformanceHistory
  86.    [CmdletBinding()]Param()
  87.    DYNAMICPARAM {
  88.       $CommandName = $MyInvocation.InvocationName
  89.            return Resolve-Autoloaded $CommandName
  90.    }#DynamicParam
  91.  
  92.    begin {
  93.       Write-Verbose "Command: $CommandName"
  94.       if(!$Script:AutoloadHash[$CommandName]) {
  95.          do {
  96.             $Alias = $CommandName
  97.             $CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
  98.             Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName"
  99.          } while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
  100.       } else {
  101.          Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
  102.       }
  103.       if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
  104.  
  105.       $ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
  106.       Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName -> $FunctionName"
  107.      
  108.      
  109.       #Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta
  110.    
  111.       $global:command = $ExecutionContext.InvokeCommand.GetCommand( $FunctionName, [System.Management.Automation.CommandTypes]::Function )
  112.       Write-Verbose "Autoloaded Command: $($Command|Out-String)"
  113.       $scriptCmd = {& $command @PSBoundParameters | Write-Output }
  114.       $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
  115.       $steppablePipeline.Begin($myInvocation.ExpectingInput)
  116.    }
  117.    process
  118.    {
  119.       Write-Verbose "Invoke-Autoloaded Process: $CommandName ($_)"
  120.       try {
  121.          if($_) {
  122.             $steppablePipeline.Process($_)
  123.          } else {
  124.             $steppablePipeline.Process()
  125.          }
  126.       } catch {
  127.          throw
  128.       }
  129.    }
  130.  
  131.    end
  132.    {
  133.       try {
  134.          $steppablePipeline.End()
  135.       } catch {
  136.          throw
  137.       }
  138.       Write-Verbose "Invoke-Autoloaded End: $CommandName"
  139.    }
  140. }#Invoke-Autoloaded
  141.  
  142.  
  143. function Get-AutoloadHelp {
  144.         [CmdletBinding()]
  145.         Param([Parameter(Mandatory=$true)][String]$CommandName)
  146.         $null = Resolve-Autoloaded $CommandName
  147.         Get-Help $CommandName
  148. }
  149.  
  150. function Resolve-Autoloaded {
  151. [CmdletBinding()]
  152. param(
  153. [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
  154. [Alias("Name")]
  155. [String]$CommandName
  156. )
  157.       $OriginalCommandName = "($CommandName)"
  158.       Write-Verbose "Command: $CommandName"
  159.       if(!$Script:AutoloadHash[$CommandName]) {
  160.          do {
  161.             $Alias = $CommandName
  162.             $CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
  163.             $OriginalCommandName += "($CommandName)"
  164.             Write-Verbose "Resolve-Autoloaded Begin: $Alias -> $CommandName"
  165.          } while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
  166.       } else {
  167.          Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
  168.       }
  169.       if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command $OriginalCommandName!" }
  170.      
  171.       Write-Verbose "Resolve-Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
  172.       $ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
  173.       Write-Verbose "Autoloading:`nScriptName: $ScriptName `nModuleName: $ModuleName `nFunctionName: $FunctionName"
  174.      
  175.       if(!$ScriptName){ $ScriptName = $CommandName }
  176.       if(!$FunctionName){ $FunctionName = $CommandName }
  177.       if($ModuleName) {
  178.          $Module = Get-Module $ModuleName
  179.       } else { $Module = $null }
  180.      
  181.      
  182.       ## Determine the command name based on the alias used to invoke us
  183.       ## Store the parameter set for use in the function later...
  184.       $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
  185.      
  186.       #$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
  187.       $externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1
  188.       Write-Verbose "Processing Script: $($externalScript |Out-String)"
  189.       $parserrors = $null
  190.       $prev = $null
  191.       $script = $externalScript.ScriptContents
  192.       [System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
  193.       [Array]::Reverse($tokens)
  194.      
  195.       $function = $false
  196.       ForEach($token in $tokens) {
  197.          if($prev -and $token.Content -eq "# SIG # Begin signature block") {
  198.             $script = $script.SubString(0, $token.Start )
  199.          }
  200.          if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -ieq $FunctionName ) {
  201.             $script = $script.Insert( $prev.Start, "global:" )
  202.             $function = $true
  203.             Write-Verbose "Globalized: $($script[(($prev.Start+7)..($prev.Start + 7 +$prev.Content.Length))] -join '')"
  204.          }
  205.          $prev = $token
  206.       }
  207.      
  208.       if(!$function) {
  209.          $script = "function global:$Functionname { $script }"
  210.       }
  211.      
  212.       if($Module) {
  213.          $script = Invoke-Expression "{ $Script }"
  214.          Write-Verbose "Importing Function into $($Module) module."
  215.          &$Module $Script | Out-Null
  216.          $command = Get-Command $FunctionName -Type Function
  217.          Write-Verbose "Loaded Module Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
  218.       } else {
  219.          Write-Verbose "Importing Function without module."
  220.          Invoke-Expression $script | out-null
  221.          $command = Get-Command $FunctionName -Type Function
  222.          Write-Verbose "Loaded Local Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
  223.       }
  224.       if(!$command) {
  225.          throw "Something went wrong autoloading the $($FunctionName) function. Function definition doesn't exist in script: $($externalScript.Path)"
  226.       }
  227.      
  228.       if($CommandName -eq $FunctionName) {
  229.          Remove-Item Alias::$($CommandName)
  230.          Write-Verbose "Defined the function $($FunctionName) and removed the alias $($CommandName)"
  231.       } else {
  232.          Set-Alias $CommandName $FunctionName -Scope Global
  233.          Write-Verbose "Defined the function $($FunctionName) and redefined the alias $($CommandName)"
  234.       }
  235.       foreach( $pkv in $command.Parameters.GetEnumerator() ){
  236.          $parameter = $pkv.Value
  237.          if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
  238.          $param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
  239.          $paramdictionary.Add($pkv.Key, $param)
  240.       }
  241.       return $paramdictionary
  242. }
  243.  
  244. function New-Autoload {
  245. [CmdletBinding()]
  246. param(
  247.    [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
  248.    [string[]]$Name
  249. ,
  250.    [Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
  251.    [Alias("BaseName")]
  252.    $Alias = $Name
  253. ,
  254.    [Parameter(Position=2,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
  255.    $Function = $Alias
  256. ,
  257.    [Parameter(Position=3,Mandatory=$false)]
  258.    [String]$Module
  259. ,
  260.    [Parameter(Mandatory=$false)]
  261.    [String]$Scope = '2'
  262.  
  263. )
  264. begin {
  265.    $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
  266.    if(!$xlr8r::Get["PSParser"]) {
  267.       if($xlr8r::AddReplace) {
  268.          $xlr8r::AddReplace( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
  269.       } else {
  270.          $null = $xlr8r::Remove( "PSParser" )
  271.          $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
  272.       }
  273.  
  274.    
  275.    }  
  276. }
  277. process {
  278.    for($i=0;$i -lt $Name.Count;$i++){
  279.       if($Alias -is [Scriptblock]) {
  280.          $a = $Name[$i] | &$Alias
  281.       } elseif($Alias -is [Array]) {
  282.          $a = $Alias[$i]
  283.       } else {
  284.          $a = $Alias
  285.       }
  286.      
  287.       if($Function -is [Scriptblock]) {
  288.          $f = $Name[$i] | &$Function
  289.       } elseif($Function -is [Array]) {
  290.          $f = $Function[$i]
  291.       } else {
  292.          $f = $Function
  293.       }
  294.      
  295.       Write-Verbose "Set-Alias $Module\$a Invoke-Autoloaded -Scope $Scope"
  296.       Set-Alias $a Invoke-Autoloaded -Scope $Scope
  297.       $Script:AutoloadHash[$a] = $Name[$i],$Module,$f
  298.       Write-Verbose "$($Script:AutoloadHash.Count)  `$AutoloadHash[$a] = $($Script:AutoloadHash[$a])"
  299.    }
  300. }
  301. }
  302.  
  303. Set-Alias Autoload New-Autoload
  304. Set-Alias LoadNow  Resolve-Autoloaded
  305.  
  306. New-Variable -Name AutoloadHash -Value @{} -Scope Script -Description "The Autoload alias-to-script cache" -Option ReadOnly -ErrorAction SilentlyContinue
  307.  
  308. Export-ModuleMember -Function New-Autoload, Invoke-Autoloaded, Get-AutoloadHelp, Resolve-Autoloaded -Alias *

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me