Introduction
You add methods to objects to give them new actions they can do, making your scripts more powerful and organized.
$object | Add-Member -MemberType ScriptMethod -Name MethodName -Value { param() <script block> }$obj = New-Object PSObject
$obj | Add-Member -MemberType ScriptMethod -Name SayHello -Value { "Hello, world!" }
$obj.SayHello()$obj = New-Object PSObject
$obj | Add-Member -MemberType ScriptMethod -Name AddNumbers -Value { param($a, $b) $a + $b }
$obj.AddNumbers(5, 7)$person = New-Object PSObject -Property @{ Name = 'Alice' }
$person | Add-Member -MemberType ScriptMethod -Name Greet -Value { "Hello, my name is $($this.Name)." }
Write-Output $person.Greet()Add-Member -MemberType ScriptMethod cmdlet do in PowerShell?Add-Member is used to add properties or methods to existing objects in PowerShell.-MemberType ScriptMethod is used, it adds a method (a function) that can be called on the object.Greet to an object $obj that returns 'Hello'?$obj = New-Object PSObject -Property @{Name='Alice'}
$obj | Add-Member -MemberType ScriptMethod -Name SayName -Value { "My name is $($this.Name)" }
$obj.SayName()$obj:
$obj = New-Object PSObject -Property @{Age=30}
Add-Member -InputObject $obj -MemberType ScriptMethod -Name GetAge -Value { return $Age }
$obj.GetAge()$Age which is undefined in this scope. To access the object's property, use $this.Age.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?Pass the test and this pattern moves unknown