PoshCode Logo PowerShell Code Repository

Require-Function by Bernd Kriszio 24 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1617"></script>download | new post

This is a bit similar to Python import module. If a function is present, nothing happens, otherwise Path is searched for a file with the functionname and the extension .ps1 and that file is dot sourced

  1. function Require-Function
  2. {
  3.   <#
  4. .SYNOPSIS
  5.     Load function when not already loaded    
  6. .DESCRIPTION
  7.     When a function is not loaded and there is a file <functionname>.ps1 in one of the directories listed
  8.     in $env:Path it is dot sourced.
  9.     To get the function in your environment you must dot source the Require-Function too.
  10. .NOTES
  11.     File Name  : Require-Function.ps1
  12.     Author     : Bernd Kriszio - http://pauerschell.blogspot.com/
  13. .PARAMETER FunctionName
  14.     The name of the function you want to import
  15. .EXAMPLE
  16.     . Require-Function <any_function_script_in_your_path>
  17. .EXAMPLE
  18.     . Require-Function New-ISEFile -verbose
  19. .EXAMPLE
  20.     . Require-Function New-ISEFile
  21. .EXAMPLE
  22.    . Require-Function unbekanntn -verbose
  23. #>
  24.    [cmdletbinding()]
  25.    param (
  26.     [string] $FunctionName
  27.     )
  28.    
  29.     if (! (Test-Path function:$FunctionName))
  30.     {
  31.         try{
  32.             Write-Verbose "Function $FunctionName not loaded"
  33.             $cmd = "$($FunctionName).ps1"
  34.             #"$cmd"
  35.             .  $cmd
  36.         }
  37.         catch
  38.         {
  39.             "$cmd could not be loaded"
  40.             break;
  41.         }
  42.         Write-Verbose "Function $FunctionName is loaded"
  43.     }
  44.     else
  45.     {
  46.         Write-Verbose "Function $FunctionName was loaded"
  47.     }
  48. }

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