#PSTip Invoking methods by using dynamic method names

Note: This tip requires PowerShell 4.0 or above.

PowerShell enables you to refer to a property of an object in a dynamic fashion:

PS> $proc = Get-Process -Id $PID
PS> $property = 'Handles'
PS> $proc.$property

PS> $property = 'Name'
PS> $proc.$property

Trying the same approach with object methods failed with an error. Starting in Windows PowerShell 4.0 it is now possible to use a variable that holds the method name and dynamically invoke it:

$fso = New-Object -ComObject Scripting.FileSystemObject

Get-ChildItem | ForEach-Object {
    $method = if ($_.PSIsContainer) {'GetFolder'} else {'GetFile'}
Filed in: Columns, Tips and Tricks Tags: , ,

2 Responses to "#PSTip Invoking methods by using dynamic method names"

  1. By the way, I wrote an article about dynamic method invocation a few years back on the Hey Scripting Guy blog: http://blogs.technet.com/b/heyscriptingguy/archive/2010/12/14/dynamic-method-invocation-in-powershell.aspx

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: