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.
- 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 )
- } }
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.
PowerShell Code Repository