Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert function to script method?

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 }
like image 348
Samselvaprabu Avatar asked Jul 01 '26 23:07

Samselvaprabu


2 Answers

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
like image 186
fdafadf Avatar answered Jul 04 '26 01:07

fdafadf


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)
like image 34
Paweł Dyl Avatar answered Jul 04 '26 01:07

Paweł Dyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!