# 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: 2060
# x-archived: 2012-01-10T10:23:27
# x-published: 2012-08-10T21:36: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 )
} }
