Invoking Methods Using Variables

PowerShell Team

You can have a lot of fun with PowerShell. 
Makes sense right – we’re busting our butts off and we get to define it so why wouldn’t we make it fun?
Your busting your butts off at your job as well so why shouldn’t your tools be fun?  Right?

In particular, our late binding of names allows you to do some really cool, really powerful stuff.  Here is an example:

PS> $d=Get-Date
PS> foreach ($p in "Day","hour","minute") {"$p :  " + $d.$p }
Day :  5
hour :  8
minute :  53

This allows you to write some very fun code.  As soon as you start doing that, you’ll pretty quickly want to do the same thing for methods but that doesn’t work as well:

PS> foreach ($p in "AddDays","AddHours","AddMinutes"){"$p :  " + $d.$p(1) }

Unexpected token ‘(‘ in expression or statement.
At line:1 char:67

Unexpected token ‘1’ in expression or statement.
At line:1 char:68

Missing closing ‘}’ in statement block.
At line:1 char:69

Unexpected token ‘)’ in expression or statement.
At line:1 char:69

 

 

 

Here is how you make it work:  you need to do is to specify the method as property and then call the Invoke() method on that property.  It sounds a little strange so lets first review what happens when you specify a method as a property

PS> $d.AddDays

MemberType          : Method
OverloadDefinitions : {System.DateTime AddDays(double value)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.DateTime AddDays(double value)
Name                : AddDays
IsInstance          : True

__________________________________________________________________________________________________________________________________
PS> $d.AddDays | Get-Member -View ALL i*

   TypeName: System.Management.Automation.PSMethod

Name       MemberType Definition                                           
—-       ———- ———-                                           
Invoke     Method     System.Object Invoke(Params System.Object[] arguments)
IsInstance Property   System.Boolean IsInstance {get;}
                     

 

 

 

With that refresher – here is how you do it:

PS> foreach ($p in "AddDays","AddHours","AddMinutes"){"$p :  " + $d.$p.Invoke(1) }

AddDays :  01/06/2009 08:53:53
AddHours :  01/05/2009 09:53:53
AddMinutes :  01/05/2009 08:54:53

 

 

Enjoy!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

0 comments

Discussion is closed.

Feedback usabilla icon