Method definitions

When we are dealing with .NET objects we have methods and properties to deal with. Properties are easy.

lets create a simple object

$str = "QWERTYUIOP"

 

put our string object into get-member to see the properties

$str | Get-Member -MemberType property

 

In this case we get one property.

Methods we can get like this

$str | Get-Member -MemberType method

 

and we find there are 33 of them on a string object.  Some of the methods can be used in different ways i.e. have different definitions. For instance the substring method has a couple of definitions

PS> $str.substring.OverloadDefinitions
string Substring(int startIndex)
string Substring(int startIndex, int length)

 

When we look at the output of get-member for a method such as Replace we get this

Replace          Method     string Replace(char oldChar, char newChar), string Replace(string oldValue, string newVa...

Ideally we want to be able to see all of the definitions.  We could use

$str | Get-Member -MemberType method | Format-Table –wrap

 

but its not easy to read.  If you want to dig into the method definitions try this

 

001
002
003
004
005
006
007
008
009
010
011
012
013

function get-methoddefinitions {
 [CmdletBinding()]
 param ($obj)
 
 $obj | Get-Member -MemberType method | select name |
 foreach {
   $_.Name
  
   $cmd = '$obj.' + "$($_.Name).Overloaddefinitions"
   Invoke-Expression -Command $cmd 
   ""
  } 
}

 

We can use string substitution to get the method name into the string and then run it with Invoke-Expression.  Note how we use single quotes on the first part of the string to prevent substitution.  Our output for the replace method becomes

Replace
string Replace(char oldChar, char newChar)
string Replace(string oldValue, string newValue)

which is easy to read. 

The function could be extended to accept a method name to avoid displaying everything.

Leave a Reply