0
0
PowerShellscripting~5 mins

Adding methods with ScriptMethod in PowerShell

Choose your learning style9 modes available
Introduction
You add methods to objects to give them new actions they can do, making your scripts more powerful and organized.
When you want to add a custom action to an existing object without creating a new class.
When you need to reuse a small piece of code as a method on multiple objects.
When you want to extend built-in objects with your own functions for easier scripting.
When you want to keep your script clean by grouping related code inside objects.
Syntax
PowerShell
$object | Add-Member -MemberType ScriptMethod -Name MethodName -Value { param() <script block> }
Use Add-Member to add a ScriptMethod to an existing object.
The script block defines what the method does when called.
Examples
Adds a method SayHello that returns a greeting string.
PowerShell
$obj = New-Object PSObject
$obj | Add-Member -MemberType ScriptMethod -Name SayHello -Value { "Hello, world!" }
$obj.SayHello()
Adds a method AddNumbers that takes two numbers and returns their sum.
PowerShell
$obj = New-Object PSObject
$obj | Add-Member -MemberType ScriptMethod -Name AddNumbers -Value { param($a, $b) $a + $b }
$obj.AddNumbers(5, 7)
Sample Program
Creates a person object with a Name property and adds a Greet method that uses the Name to say hello.
PowerShell
$person = New-Object PSObject -Property @{ Name = 'Alice' }
$person | Add-Member -MemberType ScriptMethod -Name Greet -Value { "Hello, my name is $($this.Name)." }
Write-Output $person.Greet()
OutputSuccess
Important Notes
Inside the script block, use $this to refer to the object the method belongs to.
ScriptMethod lets you add behavior to objects without defining a full class.
You can add parameters to your ScriptMethod by using param() inside the script block.
Summary
Add-Member with ScriptMethod lets you add custom methods to objects.
Use $this inside the method to access the object's properties.
This helps organize code and reuse functionality easily.