A question came up on an MVP mailing list about passing delegates of .NET methods to managed APIs in PowerShell. I covered callbacks to script blocks in a previous post, but I've never covered anything on passing regular .NET methods to APIs so here's a function I wrote to easily create Action, Action<> or Func<> delegates for any given static or instance method. The syntax is pipeline friendly and very flexible. As methods may be overloaded, you must provide a means to select an overload for the delegate. This is done by either providing a specific delegate type you wish to create, or by passing an array of types that should be used to find a compatible overload. The latter technique is more flexible because you only need to provide compatible parameters; the explicit delegate technique needs an exact match for the overload. Here are some examples of the syntax:
# Gets a delegate for a matching overload with string,string parameters.
# It will actually return func<string,object,string> which is the correct
# signature for invoking string.format with string,string.
$delegate = [string]::format | Get-Delegate string,string
# Gets a delegate for a matching overload with no parameters.
$delegate = [console]::beep | Get-Delegate @()
# Gets a delegate for a matching overload with @(int,int) parameters.
$delegate = [console]::beep | get-delegate int,int
# Gets a delegate for an explicit func[].
$delegate = [string]::format | Get-Delegate -Delegate 'func[string,object,string]'
# Gets a delegate for an explicit action[].
$delegate = [console]::writeline | Get-Delegate -Delegate 'action[int]'
# For a method with no overloads, we will choose the default method and
# create a corresponding action, action[] or func[].
$delegate = [string]::isnullorempty | get-delegate
# Gets a delegate to an instance method of a stringbuilder: Append(string)
$sb = new-object text.stringbuilder
$delegate = $sb.append | get-delegate string
Here is the function definition itself. It requires PowerShell 3.0 (in public beta right now) due to some new language features but in theory it could be modified to support PowerShell 2.0. It's also available on PoshCode.
#requires -version 3
function Get-Delegate {
<#
.SYNOPSIS
Create an action[] or func[] delegate for a psmethod reference.
.DESCRIPTION
Create an action[] or func[] delegate for a psmethod reference.
.PARAMETER Method
A PSMethod reference to create a delegate for. This parameter accepts pipeline input.
.PARAMETER ParameterType
An array of types to use for method overload resolution. If there are no overloaded methods
then this array will be ignored but a warning will be omitted if the desired parameters were
not compatible.
.PARAMETER DelegateType
The delegate to create for the corresponding method. Example: [string]::format | get-delegate -delegatetype func[int,string]
.INPUTS System.Management.Automation.PSMethod, System.Type[]
.EXAMPLE
$delegate = [string]::format | Get-Delegate string,string
Gets a delegate for a matching overload with string,string parameters.
It will actually return func
Here are some tests to demonstrate the various cases covered. They were pretty much essential while I was tweaking the script.
# general test function
function Assert-True {
param(
[parameter(position=0, mandatory=$true)]
[validatenotnull()]
[scriptblock]$Script,
[parameter(position=1)]
[validatenotnullorempty()]
[string]$Name = "Assert-True"
)
$eap = $ErrorActionPreference
Write-Host -NoNewline "Assert-True [ $Name ] "
try {
$erroractionpreference = "stop"
if ((& $script) -eq $true) {
write-host -ForegroundColor Green "[PASS]"
return
}
$reason = "Assert failed."
}
catch {
$reason = "Error: $_"
}
finally {
$ErrorActionPreference = $eap
}
write-host -ForegroundColor Red "[FAIL] " -NoNewline
write-host "Reason: '$reason'"
}
#
# static methods
#
assert-true {
$delegate = [string]::format | Get-Delegate -Delegate 'func[string,object,string]'
$delegate.invoke("hello, {0}", "world") -eq "hello, world"
} -name "[string]::format | get-delegate -delegate 'func[string,object,string]'"
assert-true {
$delegate = [console]::writeline | Get-Delegate -Delegate 'action[int]'
$delegate -is [action[int]]
} -name "[console]::writeline | get-delegate -delegate 'action[int]'"
assert-true {
$delegate = [string]::format | Get-Delegate string,string
$delegate.invoke("hello, {0}", "world") -eq "hello, world"
} -name "[string]::format | get-delegate string,string"
assert-true {
$delegate = [console]::beep | Get-Delegate @()
$delegate -is [action]
} -name "[console]::beep | get-delegate @()"
assert-true {
$delegate = [console]::beep | Get-Delegate -DelegateType action
$delegate -is [action]
} -name "[console]::beep | Get-Delegate -DelegateType action"
assert-true {
$delegate = [string]::IsNullOrEmpty | get-delegate
$delegate -is [func[string,bool]]
} -name "[string]::IsNullOrEmpty | get-delegate # single overload"
assert-true {
$delegate = [string]::IsNullOrEmpty | get-delegate string
$delegate -is [func[string,bool]]
} -name "[string]::IsNullOrEmpty | get-delegate string # single overload"
#
# instance methods
#
assert-true {
$sb = new-object text.stringbuilder
$delegate = $sb.Append | get-delegate string
$delegate -is [System.Func[string,System.Text.StringBuilder]]
} -name "`$sb.Append | get-delegate string"
assert-true {
$sb = new-object text.stringbuilder
$delegate = $sb.AppendFormat | get-delegate string, int, int
$delegate -is [System.Func[string,object,object,System.Text.StringBuilder]]
} -name "`$sb.AppendFormat | get-delegate string, int, int"