Challenge - 5 Problems
ScriptMethod Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this PowerShell script adding a ScriptMethod?
Consider this PowerShell code that adds a ScriptMethod to a custom object. What will be the output when calling the method?
PowerShell
$obj = New-Object PSObject -Property @{Name='Alice'}
$scriptBlock = { "Hello, $($this.Name)!" }
$obj | Add-Member -MemberType ScriptMethod -Name Greet -Value $scriptBlock
$obj.Greet()Attempts:
2 left
💡 Hint
Remember that $this inside a ScriptMethod refers to the object itself.
✗ Incorrect
The ScriptMethod uses $this to access the object's properties. Since Name is 'Alice', the method returns 'Hello, Alice!'.
📝 Syntax
intermediate2:00remaining
Which option correctly adds a ScriptMethod to a PowerShell object?
You want to add a ScriptMethod named 'SayBye' to a PSObject that returns 'Goodbye, !'. Which code snippet is correct?
Attempts:
2 left
💡 Hint
Inside ScriptMethod, use $this to refer to the object itself.
✗ Incorrect
Option D correctly uses $this.Name inside the script block to access the object's Name property. Other options use invalid syntax or miss the $this reference.
🔧 Debug
advanced2:00remaining
Why does this ScriptMethod fail to access the object's property?
Given this code, why does calling $obj.Hello() produce an error?
$obj = New-Object PSObject -Property @{Name='Bob'}
$sb = { "Hi, $Name!" }
$obj | Add-Member -MemberType ScriptMethod -Name Hello -Value $sb
$obj.Hello()
Attempts:
2 left
💡 Hint
Think about how to access object properties inside ScriptMethod script blocks.
✗ Incorrect
Inside a ScriptMethod, $this refers to the object. $Name alone is undefined, causing an error. Using $this.Name fixes the issue.
🚀 Application
advanced2:00remaining
How to add a ScriptMethod that modifies an object property?
You want to add a ScriptMethod 'SetAge' to a PSObject that sets its 'Age' property to a given value. Which code correctly does this?
Attempts:
2 left
💡 Hint
Use $this to refer to the object and param() to accept arguments.
✗ Incorrect
Option B correctly defines a parameter and assigns it to $this.Age. Other options either miss $this or have invalid syntax.
🧠 Conceptual
expert2:00remaining
What happens if you add multiple ScriptMethods with the same name to a PSObject?
If you add two ScriptMethods named 'Action' to the same PSObject, what will be the result when calling $obj.Action()?
Attempts:
2 left
💡 Hint
Add-Member throws an error when adding a member with a name that already exists unless -Force is specified.
✗ Incorrect
PowerShell throws an error when trying to add a duplicate ScriptMethod unless the -Force parameter is used. By default, Add-Member does not overwrite existing members.