#PSTip Invoking methods with New-Object

Note: This tip requires PowerShell 2.0 or above.

Starting with PowerShell 2.0 we can create new objects and set property values with the Property parameter. For instance, launch MS Word and set its visibility.

New-Object -ComObject Word.Application -Property @{Visible=$true}

Did you know that you can also invoke objects methods? The next example creates a new instance of IE and navigates to a website.

$property = @{Visible=$true; Navigate2='http://PowerShellMagazine.com'}
New-Object -ComObject InternetExplorer.Application -Property $property

In the following example we create a new ArrayList object and invoke the AddRange method to create 10 elements with corresponding values from 1 to 10.

New-Object System.Collections.ArrayList -Property @{AddRange = 1..10}

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: