Sunday, October 21, 2007

Call-Method

When you are using PowerShell, you often have to call a method. Calling a method is not difficult -
$s="abc"
$s.toUpper()
ABC
but you kind of have to change gear - you have to switch from the PowerShell way of doing things to the .Net / programmatic way. This is no problem if you know it - but it is hard to teach someone, especially if they do not have a programming background.

So, why not create a function and do it the PowerShell way? The function is actually very simple -

function Call-Method($method) { process { $m=$_.$method; $m.invoke($args) } }


And add an alias to minimize the typing -
new-alias -force cm Call-Method


Now it is simple to call methods without dots and parenthesises -
"abc" | cm toupper
ABC
"abc" | cm indexof b
1
"abc" | cm substring 1
bc
$s="abc"
$s[($s | cm indexof b)]
b

Have fun!

1 comment:

Anonymous said...

Nicely done. Great insight.