Bird
0
0

What will be the output of this PowerShell code?

medium📝 Command Output Q13 of 15
PowerShell - Working with Objects
What will be the output of this PowerShell code?
$obj = New-Object PSObject -Property @{Name='Alice'}
$obj | Add-Member -MemberType ScriptMethod -Name SayName -Value { "My name is $($this.Name)" }
$obj.SayName()
AMy name is
BMy name is $this.Name
CMy name is Alice
DError: Property 'Name' not found
Step-by-Step Solution
Solution:
  1. Step 1: Understand object and method

    $obj has a property Name='Alice'. The ScriptMethod SayName uses $this.Name to access that property.
  2. Step 2: Evaluate method call output

    Calling $obj.SayName() runs the script block, replacing $($this.Name) with 'Alice', so output is 'My name is Alice'.
  3. Final Answer:

    My name is Alice -> Option C
  4. Quick Check:

    $this.Name accesses property correctly [OK]
Quick Trick: Use $this to access object properties inside ScriptMethod [OK]
Common Mistakes:
  • Expecting literal $this.Name output
  • Confusing property access syntax
  • Thinking method won't access object properties

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes