Accessing Internet Explorer

by Apr 3, 2009

Accessing Internet Explorer can be useful for obtaining Web content. The usual approach uses a COM object called InternetExplorer.Application like this:

$ie = New-Object -comObject InternetExplorer.Application
$ie.visible = $true

Unfortunately, this approach fails when you use IE with enhanced security (Vista UAC for example). While you can open IE and navigate to the Web page, you will lose access to the document property once the Web site is loaded because the COM object works only for local files. Once you navigate to a Web page, IE launches again with lower privileges, and PowerShell has no way of accessing the new instance.

To work around this issue, you can use yet another COM object called Shell.Application. It returns all Explorer windows, including all open IE windows. All you need do is pick the IE window you need, by specifying a keyword found in its title bar.

The following example launches a Web page and then waits until a browser window opened with the word "PowerShell" in its title bar. Next, the code returns the IE object and accesses the Web page content.

& "$env:programfilesInternet Exploreriexplore.exe" ''

$win = New-Object -comObject Shell.Application
$try = 0
$ie2 = $null
do {
Start-Sleep -milliseconds 500
$ie2 = @($ | ? { $_.locationName -like '*PowerShell*' })[0]
$try ++
if ($try -gt 20) {
Throw "Web Page cannot be opened."
} while ($ie2 -eq $null)