#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
485

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

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'}
    $fso.$method($_.FullName)
}

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: