functionNew-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!' Get-Process }
# create new function in function: drive and set scope to "script:" $null = New-Item-Path function: -Name"script:$Name"-Value$Code }
# 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 functiondefineddynamically. I can do whatever you want!
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName -------------------------------------------- 2191833841027689,52130881 AppleMobileDeviceProcess 5743529972845003,5085481 ApplicationFrameHost 14791376564444720 armsvc
# use -Force to overwrite existing functions $null = New-Item-Force-Path function: -Name"script:Test-This"-Value@" 'Source code can be a string.' $a$c$b "@