Link to home
Start Free TrialLog in
Avatar of lhutton
lhutton

asked on

Determine whether to use an existing or new instance of IE

I had this question after viewing Open successive arrays of URLs in IE.

I am using this code to determine whether to use an existing or new instance of IE:
$newInstance = $false
if (Get-Process iexplore -ea silentlycontinue | Where-Object {$_.MainWindowTitle -ne ""}) {
    $ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" } | Select-Object -First 1
    $newInstance = $false
} else {
    $ie = New-Object -COM "InternetExplorer.Application"
    $newInstance = $true
}

# Elsewhere, I open an array of sites depending on what tabs are already open
foreach ($tab in (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" }) {
    if ($tab.LocationURL.Contains("~"))
    { $search = $true; break }
}

Open in new window

If a tab is open that has specified text in its title, how can I ignore that instance of IE, and use a second instance to open an array of sites in? I have tried this:
$ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" -and $_.LocationName -like ""}
if ($null -ne $ie) {
    $ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" } | Select-Object -First 1
    $newInstance = $false
} else {
    $ie = New-Object -COM "InternetExplorer.Application"
    $newInstance = $true
}

Open in new window

Avatar of lhutton
lhutton

ASKER

I have got it working; improvements appreciated.

$newInstance = $false
if (Get-Process iexplore -ea silentlycontinue | Where-Object {$_.MainWindowTitle -ne ""}) {
    if ((New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" -and $_.LocationName -notlike "**" }) {
        $ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" } | Select-Object -First 1
        $newInstance = $false
    } else {
        $ie = New-Object -COM "InternetExplorer.Application"
        $newInstance = $true
    }
} else {
    $ie = New-Object -COM "InternetExplorer.Application"
    $newInstance = $true
}

Open in new window

Avatar of Qlemo
I assume you removed something between the two wildcards in -and $_.LocationName -notlike "**" , because it does not make sense as posted. "*" and "**" match all strings, so that condition should always be false.  Your condition probably looks like -and $_.LocationName -notlike "*abc*" .
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lhutton

ASKER

Excellent; thank you! (Yes, I removed the text between the two wildcards.)