Creating PowerShell Functions Dynamically

by Aug 18, 2020

New-Item can create new things on any PowerShell drive, including the function: drive that holds all PowerShell functions.

If you’d like, you can define new functions dynamically inside your code. These new functions would then exist only in the scope where they were defined. To make them script-global, add the script: scope identifier. Here is an example:

function New-DynamicFunction
   # creates a new function dynamically
   $Name = 'Test-NewFunction'
   $Code = { 
      "I am a new function defined dynamically."
      Write-Host -ForegroundColor Yellow 'I can do whatever you want!'

   # create new function in function: drive and set scope to "script:"
   $null = New-Item -Path function: -Name "script:$Name" -Value $Code

To test-drive this, run New-DynamicFunction. Once you did, there is a new function called Test-NewFunction:

# this function does not (yet) exist:
PS> Test-NewFunction
Test-NewFunction : The term 'Test-NewFunction' is not recognized as the name of a cmdlet, function, script 
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path 
is correct and try again.
PS> New-DynamicFunction
# now the function exists:
PS> Test-NewFunction
I am a new function defined dynamically.
I can do whatever you want!
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName                                      
-------  ------    -----      -----     ------     --  -- -----------                                      
    219      18     3384      10276      89,52  13088   1 AppleMobileDeviceProcess                         
    574      35    29972      84500       3,50   8548   1 ApplicationFrameHost                             
    147       9     1376       5644              4472   0 armsvc  

Note how we defined the code of the new function as a script block in curly brackets. This is not required. You can also define it as plain-text string which may provide you with even more flexibility to compose the source code of your new function:

$a = "not"
$b = "AD"
$c = "EP"

# use -Force to overwrite existing functions
$null = New-Item -Force -Path function: -Name "script:Test-This" -Value @"
'Source code can be a string.'


Note also that New-Item will not overwrite existing functions unless you specify -Force.

Twitter This Tip! ReTweet this Tip!