Bird
0
0

Identify the error in this code:

medium📝 Debug Q6 of 15
PowerShell - Working with Objects
Identify the error in this code:
$obj = [PSCustomObject]@{Name='Sam'}; $obj.Age = 25
AThe syntax for creating PSCustomObject is wrong
BAge property must be defined in the hashtable initially
CYou cannot add new properties after creation this way
DNo error, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Create PSCustomObject with only Name property

    The object has only Name defined initially.
  2. Step 2: Try to add Age property by direct assignment

    Direct assignment to a new property does not add it to PSCustomObject.
  3. Step 3: This causes an error or property is not added

    New properties must be added with Add-Member, not direct assignment.
  4. Final Answer:

    You cannot add new properties after creation this way -> Option C
  5. Quick Check:

    Adding new properties requires Add-Member = You cannot add new properties after creation this way [OK]
Quick Trick: Use Add-Member to add new properties after object creation [OK]
Common Mistakes:
  • Assuming direct assignment adds new properties
  • Ignoring error messages
  • Confusing property update with property addition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes