0
0
PowerShellscripting~5 mins

Adding methods with ScriptMethod in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a ScriptMethod in PowerShell?
A ScriptMethod is a way to add a custom method to an object in PowerShell using a script block. It lets you extend objects with new behaviors.
Click to reveal answer
beginner
How do you add a ScriptMethod to an existing object in PowerShell?
Use the Add-Member cmdlet with the -MemberType ScriptMethod parameter, specifying the method name and a script block for the method's code.
Click to reveal answer
beginner
Example: What does this code do? $person = New-Object PSObject -Property @{Name='Anna'} $person | Add-Member -MemberType ScriptMethod -Name Greet -Value { "Hello, $($this.Name)!" } $person.Greet()
It creates a new object with a Name property 'Anna'. Then it adds a method called Greet that returns a greeting string using the Name. Calling $person.Greet() outputs: Hello, Anna!
Click to reveal answer
intermediate
Why use $this inside a ScriptMethod in PowerShell?
$this refers to the current object the method is attached to. It lets the method access the object's properties and other data.
Click to reveal answer
beginner
Can you add multiple ScriptMethods to the same object?
Yes, you can add as many ScriptMethods as you want to an object using Add-Member. Each method can have its own name and script block.
Click to reveal answer
Which cmdlet is used to add a ScriptMethod to an object in PowerShell?
ANew-Method
BAdd-Member
CSet-Method
DInvoke-Method
In a ScriptMethod, what does $this represent?
AThe method's parameters
BThe global scope
CThe current object the method belongs to
DThe script file
What type of member do you specify to Add-Member to add a method with a script block?
AScriptMethod
BAliasProperty
CNoteProperty
DScriptProperty
What will this code output? $car = New-Object PSObject -Property @{Make='Ford'} $car | Add-Member -MemberType ScriptMethod -Name ShowMake -Value { "Make is $($this.Make)" } $car.ShowMake()
AMake is Ford
BMake is $this.Make
CError: Method not found
DMake is
Can ScriptMethods access properties of the object they are added to?
AOnly if properties are global
BNo, they are independent
COnly if passed as parameters
DYes, using $this
Explain how to add a custom method to a PowerShell object using ScriptMethod.
Think about how you tell PowerShell to add a new behavior to an object.
You got /5 concepts.
    Describe the role of $this inside a ScriptMethod in PowerShell and why it is important.
    Consider how a method knows which object's data to use.
    You got /4 concepts.