I have a powershell function, is there any way to convert it into a script method?
function Do-Something {
Param(
$p1,
$p2
)
[...]
}
I am trying to convert it to script method in below fashion, but it throws exception.
$obj | add-member-membertype scriptmethod { $function:Do-Something }
This code shows two examples. In my opinion the first Add-Member shows better approach which is more OOP.
function Convert-PersonToText
{
param($Person)
'{0} {1}' -f $Person.FirstName, $Person.LastName
}
function Print-Something
{
Write-Host 'Something'
}
function New-Person
{
param($FirstName, $LastName)
$result = '' | select FirstName, LastName
$result.FirstName = $FirstName
$result.LastName = $LastName
Add-Member -InputObject $result -MemberType ScriptMethod -Name 'ToText' -Value { Convert-PersonToText -Person $this }
Add-Member -InputObject $result -MemberType ScriptMethod -Name 'Print' -Value ((Get-Command -Name 'Print-Something').ScriptBlock)
$result
}
$person = New-Person -FirstName 'John' -LastName 'Smith'
$person.ToText() | Out-Host
$person.Print()
Output:
John Smith
Something
Here is another approach (you can mix it with @fdafadf solution):
function Do-Something { param($p1) Write-Host $p1 }
$obj = @{}
$obj | Add-Member -MemberType ScriptMethod -Name "DoSomething" -Value ${function:Do-Something}
$obj.DoSomething(3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With