PowerShell for Windows Admins

May 19 2011   12:31PM GMT

Method definitions

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: