Powershell

Table of Contents

.COM



Creating COM Objects with New-Object

You can use New-Object to work with Component Object Model (COM) components. Components range from the various libraries included with Windows Script Host (WSH) to ActiveX applications such as Internet Explorer that are installed on most systems.

New-Object uses .NET Framework Runtime-Callable Wrappers to create COM objects, so it has the same limitations that .NET Framework does when calling COM objects. To create a COM object, you need to specify the ComObject parameter with the Programmatic Identifier or ProgId of the COM class you want to use. A complete discussion of the limitations of COM use and determining what ProgIds are available on a system is beyond the scope of this user's guide, but most well-known objects from environments such as WSH can be used within Windows PowerShell.

Many applications (including the Microsoft Office family of applications and Internet Explorer) can be automated by using COM. Internet Explorer illustrates some of the typical techniques and issues involved in working with COM-based applications.

$InternetExplorer = New-Object -ComObject InternetExplorer.Application


This command starts Internet Explorer, but does not make it visible. If you type Get-Process, you can see that a process named iexplore is running. In fact, if you exit Windows PowerShell, the process will continue to run. You must reboot the computer or use a tool like Task Manager to end the iexplore process.

By typing $ie | Get-Member, you can view properties and methods for Internet Explorer. To see the Internet Explorer window, set the Visible property to $true by typing:

$InternetExplorer.Visible = $true


You can then navigate to a specific Web address by using the Navigate method:

$InternetExplorer.Navigate("https://docs.microsoft.com/en-us/powershell/scripting/getting-started/cookbooks/creating-.net-and-com-objects--new-object-?view=powershell-6")


To close Internet Explorer from within PowerShell, call its Quit() method:
This will force it to close. The $ie variable no longer contains a valid reference even though it still appears to be a COM object. If you attempt to use it, you will get an automation error. There is no standard with .COM objects on how each object reacts with closing. It is a trial and error basis and often you will have to search online to find the best practice for each .COM object.

$InternetExplorer.Quit()


All .COM Objects

A list of all .COM objects can be found by querying the software local machine registry entry by running the below code.

Get-childitem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object {$_.PSChildName -match '^\w+\.\w+$' -and
(Get-ItemProperty "$($_.PSPath)\CLSID" -ErrorAction SilentlyContinue)} | Format-Table PSChildName



Visit next page to learn about - Functions