PowerShell for Windows Admins

Apr 23 2018   4:53AM GMT

Change a function definition

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: