0
0
PowerShellscripting~10 mins

Adding methods with ScriptMethod in PowerShell - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a ScriptMethod named 'Greet' to the object $obj.

PowerShell
$obj.PSObject.Members.Add((New-Object System.Management.Automation.PSMethod('Greet', [1])))
Drag options to blanks, or click blank then click option'
A{ param() 'Hello!' }
B{ Write-Host 'Hello!' }
C{ return 'Hi' }
D{ 'Hello World' }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Write-Host inside the script block instead of returning a value.
Not using a script block as the second argument.
Omitting param() in the script block.
2fill in blank
medium

Complete the code to call the 'Greet' method on the object $obj.

PowerShell
$message = $obj.[1]()
Drag options to blanks, or click blank then click option'
ASayHello
BGreet
CHello
DSpeak
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name than the one added.
Forgetting the parentheses to call the method.
3fill in blank
hard

Fix the error in adding a ScriptMethod that returns the object's name property.

PowerShell
$obj.PSObject.Members.Add((New-Object System.Management.Automation.PSMethod('GetName', [1])))
Drag options to blanks, or click blank then click option'
A{ param() $Name }
B{ return $obj.Name }
C{ param() return $this.Name }
D{ $this.Name }
Attempts:
3 left
💡 Hint
Common Mistakes
Using $obj inside the script block which is not defined there.
Omitting param() causing errors.
Not returning the value explicitly.
4fill in blank
hard

Fill the blank to add a ScriptMethod 'AddNumbers' that takes two parameters and returns their sum.

PowerShell
$obj.PSObject.Members.Add((New-Object System.Management.Automation.PSMethod('AddNumbers', [1])))
Drag options to blanks, or click blank then click option'
Areturn $a + $b
B{ $a + $b }
C$a + $b
D{ param($a, $b) $a + $b }
Attempts:
3 left
💡 Hint
Common Mistakes
Not defining parameters in the script block.
Omitting the script block syntax {}.
Using incorrect syntax for the script block.
5fill in blank
hard

Fill all three blanks to create an object $obj with a ScriptMethod 'Describe' that returns a string with the object's Name and Age.

PowerShell
$obj = New-Object PSObject -Property @{ Name = 'Alice'; Age = 30 }

$scriptBlock = [1]

$obj.PSObject.Members.Add((New-Object System.Management.Automation.PSMethod('Describe', $scriptBlock)))

$result = $obj.[2]()

Write-Output [3]
Drag options to blanks, or click blank then click option'
A{ param() "Name: $($this.Name), Age: $($this.Age)" }
BDescribe
C$result
DDescribe()
Attempts:
3 left
💡 Hint
Common Mistakes
Not using $this to access properties inside the script block.
Calling the method incorrectly without parentheses.
Trying to output the method name instead of the result variable.