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?
✗ Incorrect
Add-Member is the cmdlet used to add properties or methods, including ScriptMethods, to objects.
In a ScriptMethod, what does $this represent?
✗ Incorrect
$this refers to the object instance that owns the ScriptMethod, allowing access to its properties.
What type of member do you specify to Add-Member to add a method with a script block?
✗ Incorrect
ScriptMethod is the member type used to add a method defined by a script block.
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()
✗ Incorrect
The ScriptMethod accesses the Make property via $this and returns 'Make is Ford'.
Can ScriptMethods access properties of the object they are added to?
✗ Incorrect
ScriptMethods use $this to access the object's properties and data.
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.