Blog Archives

Inspect Methods in PowerShell


*EDIT: Code updated (Thanks Rob)

So the more you use PowerShell the less you want to leave it. When you end up with an object that you have no clue how to use you’ll likely use Get-Member to inspect it. Once you see what members it has and find a method you’d like to use you need to figure out what the params are.

$str = “hello”

$str | get-member

We can see that string has a bunch of methods and perhaps we want to use the compare but don’t know what the different overloads are so we can take a peek at them

$str.compare

You’ll notice there is () on that method call, and that’s what triggers PowerShell to show the different ways to use that method.

One problem I have with this is that some of them are so long you can’t see what belongs to what so here is my first attempt at showing it cleanly.

[string]::Compare.OverloadDefinitions -replace ‘\(‘,”`n`t ” -replace ‘,|\)’,”`n`t”

Thanks Rob for the shorter code.

Whats next? A function to do this.

function Format-Definition

{

[CmdletBinding()]

Param

(

[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]

[System.Management.Automation.PSMethod] $method

)

$defs = $method.OverloadDefinitions

foreach($def in $defs)

{

if($def -like “*()”)

{Write-Host $def -f 6}

else

{

$splits = $def -split ‘\(|\)|,’

write-host $splits[0] -f 6

$splits[1..100] | %{$rtn = $_.trim() -split ” ”

Write-host “`t$($rtn[0]) ” -F 8 -NoNewline

write-host $rtn[1]

}}}}

$str.compare | format-definition

Much better! Well, except for the colors, blame Rob for that :)

I don’t use the default color scheme so I figured I’d let you change that yourselves.