PoshCode Logo PowerShell Code Repository

Invoke-Generic by Joel Bennett 18 months ago
View followups from Joel Bennett | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2060"></script>download | new post

Invoke generic method definitions (including static methods) from PowerShell.
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.

  1. function Invoke-Generic {
  2. #.Synopsis
  3. #  Invoke Generic method definitions via reflection:
  4. [CmdletBinding()]
  5. param(
  6.    [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
  7.    [Alias('On','Type')]
  8.    $InputObject
  9. ,
  10.    [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
  11.    [Alias('Named')]
  12.    [string]$MethodName
  13. ,
  14.    [Parameter(Position=2)]
  15.    [Alias('Returns')]
  16.    [Type]$ReturnType
  17. ,
  18.    [Parameter(Position=3, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
  19.    [Object[]]$WithArgs
  20. )
  21. process {
  22.    $Type = $InputObject -as [Type]
  23.    if(!$Type) { $Type = $InputObject.GetType() }
  24.    
  25.    [Type[]]$ArgumentTypes = $withArgs | % { $_.GetType() }  
  26.    [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
  27.    
  28.    $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($returnType).Invoke( $on, $Arguments )
  29. } }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me