I've created a Open-InternetExplorer
function that creates an IE COM object, navigates to a URL, sets IE as the foreground window, and optionally full screen.
It should be noted that when the -InForeground
switch is used a call is made to the native SetForegroundWindow Win32 API. There are some situations in which this function will not change the foreground window. These situations are outlined in the MSDN documentation for the function.
function Add-NativeHelperType
{
$nativeHelperTypeDefinition =
@"
using System;
using System.Runtime.InteropServices;
public static class NativeHelper
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static bool SetForeground(IntPtr windowHandle)
{
return NativeHelper.SetForegroundWindow(windowHandle);
}
}
"@
if(-not ([System.Management.Automation.PSTypeName] "NativeHelper").Type)
{
Add-Type -TypeDefinition $nativeHelperTypeDefinition
}
}
function Open-InternetExplorer
{
Param
(
[Parameter(Mandatory=$true)]
[string] $Url,
[switch] $InForeground,
[switch] $FullScreen
)
if($InForeground)
{
Add-NativeHelperType
}
$internetExplorer = new-object -com "InternetExplorer.Application"
$internetExplorer.navigate($Url)
$internetExplorer.Visible = $true
$internetExplorer.FullScreen = $FullScreen
if($InForeground)
{
[NativeHelper]::SetForeground($internetExplorer.HWND)
}
return $internetExplorer
}
While the script provided should work, there are some potential issues in relation to resource management.
I'm not sure if I need to do anything specific in relation to returning the COM object. It's possible that either .NET or PowerShell handles this itself, but if not, there's a possibility of a resource leak.
I'm also unsure what I should do (if anything) in relation to making sure that InternetExplorer.HWND
is valid before it's passed into SetForegroundWindow
Example Usage:
. .\Open-InternetExplorer.ps1
Open-InternetExplorer -Url www.example.com -FullScreen -InForeground
PSVersion
returns 3.0. Thanks!