Bird
0
0

Which code correctly implements this?

hard📝 Application Q15 of 15
PowerShell - Working with Objects
You want to add a ScriptMethod FullName to an object $person that has properties FirstName and LastName. The method should return the full name with a space between first and last names. Which code correctly implements this?
A$person | Add-Member -MemberType ScriptMethod -Name FullName -Value { "$($this.FirstName) $($this.LastName)" }
B$person | Add-Member -MemberType ScriptProperty -Name FullName -Value { "$($this.FirstName) $($this.LastName)" }
C$person | Add-Member -MemberType ScriptMethod -Name FullName -Value { $this.FirstName + $this.LastName }
D$person | Add-Member -MemberType ScriptMethod -Name FullName -Value { return "$this.FirstName $this.LastName" }
Step-by-Step Solution
Solution:
  1. Step 1: Confirm correct MemberType and method body

    The method must be a ScriptMethod, not ScriptProperty.
  2. Step 2: Check string concatenation and property access

    $person | Add-Member -MemberType ScriptMethod -Name FullName -Value { "$($this.FirstName) $($this.LastName)" } uses string interpolation with $($this.FirstName) and $($this.LastName) separated by space, which correctly returns full name.
  3. Step 3: Analyze other options

    $person | Add-Member -MemberType ScriptMethod -Name FullName -Value { $this.FirstName + $this.LastName } concatenates without space. $person | Add-Member -MemberType ScriptMethod -Name FullName -Value { return "$this.FirstName $this.LastName" } uses return but misses $() around variables, so variables won't expand properly.
  4. Final Answer:

    $person | Add-Member -MemberType ScriptMethod -Name FullName -Value { "$($this.FirstName) $($this.LastName)" } -> Option A
  5. Quick Check:

    Use string interpolation with $() for properties [OK]
Quick Trick: Use "$($this.Prop) $($this.Prop)" for spaced string in ScriptMethod [OK]
Common Mistakes:
  • Using ScriptProperty instead of ScriptMethod
  • Concatenating strings without space
  • Not using $() for property expansion inside strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes