3

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 }

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

@fdafdaf can function in another module be used here?
In second Add-Member approach you can use only script modules (not binary modules). In the first Add-Member example you can use anything.
2

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)

3 Comments

Dyl how to param in this approach?
There is already a param. DoSomething(3) is called, 3 becomes $p1 and goes directly to Write-Host
oh then while defining we can just add the function name. While calling we can pass param. Isn’t it? Will this approach works if function is in different file ( or in different psm1)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.