PoshCode Archive  Artifact [bb13070973]

Artifact bb13070973bc298d2aaf3361105d95594b1904840d8b4ec2a3bf6bbc8d188e3d:

  • File Invoke-Generic.ps1 — part of check-in [9e80060b0f] at 2018-06-10 13:44:02 on branch trunk — Invoke generic method definitions (including static methods) from PowerShell. (user: Joel Bennett size: 1441)

# encoding: ascii
# api: powershell
# title: Invoke-Generic
# description: Invoke generic method definitions (including static methods) from PowerShell.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Invoke-Generic
# x-poshcode-id: 4638
# x-archived: 2013-11-27T10:04:54
# x-published: 2013-11-25T10:42:00
#
# I know there’s a bunch of documentation missing, but it’s bedtime, and I’ll have to write it later. No reason for you to wait to have such an awesome trick.
#
function Invoke-Generic {
#.Synopsis
#  Invoke Generic method definitions via reflection:
[CmdletBinding()]
param( 
   [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
   [Alias('On','Type')]
   $InputObject
,
   [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
   [Alias('Named')]
   [string]$MethodName
,
   [Parameter(Position=2)]
   [Alias('Returns')]
   [Type]$ReturnType
, 
   [Parameter(Position=3, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
   [Object[]]$WithArgs
)
process {
   $Type = $InputObject -as [Type]
   if(!$Type) { $Type = $InputObject.GetType() }
   
   [Type[]]$ArgumentTypes = $withArgs | % { $_.GetType() }   
   [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
   
   $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($returnType).Invoke( $on, $Arguments )
} }