Bird
0
0

What will be the output of this PowerShell code?

medium📝 Predict Output Q4 of 15
PowerShell - Working with Objects
What will be the output of this PowerShell code?
$obj = New-Object PSObject -Property @{Name='John'}
$obj | Add-Member -MemberType ScriptMethod -Name GetGreeting -Value { "Hello, $($this.Name)!" }
$obj.GetGreeting()
AHello, $($this.Name)!
BHello, John!
CError: Method not found
DHello, !
Step-by-Step Solution
Solution:
  1. Step 1: Understand object and method creation

    $obj has a property Name='John' and a ScriptMethod GetGreeting that returns a greeting using $this.Name.
  2. Step 2: Evaluate method call output

    Calling $obj.GetGreeting() runs the script block, replacing $this.Name with 'John', so output is 'Hello, John!'.
  3. Final Answer:

    Hello, John! -> Option B
  4. Quick Check:

    ScriptMethod uses $this to access properties = A [OK]
Quick Trick: Use $this inside ScriptMethod to access object properties [OK]
Common Mistakes:
  • Expecting literal string without variable expansion
  • Not using $this to access properties
  • Confusing ScriptMethod with property

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes