PoshCode Archive  Artifact [0050a6ce74]

Artifact 0050a6ce7487d67d61a3b4411937e364a55d23a51f517dbde85e7fe62054cdc8:

  • File Invoke-Generic.ps1 — part of check-in [3cafa218f1] at 2018-06-10 13:04:38 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: 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 )
} }