Search code examples
powershellpowershell-3.0powershell-5.0

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 }

Solution

  • 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