Functions in PowerShell are based on scriptblocks and as I showed in my session at the recent PowerShell Summit its possible to change a function definition.
Let’s start with a simple function:
PS> function f1 {
>> $x = 1
>> $y = 2
>> $x + $y
>> }
PS> f1
3
Our function just adds two numbers and outputs the result.
Digging into functions
PS> Get-Item -Path function:\f1 | Format-List *
PSPath : Microsoft.PowerShell.Core\Function::f1
PSDrive : Function
PSProvider : Microsoft.PowerShell.Core\Function
PSIsContainer : False
HelpUri :
ScriptBlock :
$x = 1
$y = 2
$x + $y
CmdletBinding : False
DefaultParameterSet :
Definition :
$x = 1
$y = 2
$x + $y
Options : None
Description :
Verb :
Noun :
HelpFile :
OutputType : {}
Name : f1
CommandType : Function
Source :
Version :
Visibility : Public
ModuleName :
Module :
RemotingCapability : PowerShell
Parameters : {}
ParameterSets : {}
You’ll see a scriptblock property that is the equivalent of the function definition
This means you can change the function definition by changing the scriptblock
PS> $function:f1 = {
>> $x = 2
>> $y = 3
>> $x * $y
>> }
PS> f1
6
The function has been changed to output the product of the two numbers instead of the sum.
Just one of the many things that scriptblocks can do for you