Controlling Internet Explorer object from PowerShell

NOTE: The site must be in the Trusted Sites Zone for this script to work – James Brundage [MSFT] January 5th, 2009


The following example shows how to display all the processes in an IE window and highlight the ones with memory usage of greater than or equal to the specified value.



$oIE=new-object -com internetexplorer.application
$oIE.navigate2(“About:blank”)
while ($oIE.busy) {
    sleep -milliseconds 50
}
$oIE.visible=$true
$procList=ps |select-object ProcessName,Handles,NPM,PM,WS,VM,CPU,Id |convertto-html


$oDocBody=$oIE.document.documentelement.lastchild ;


#populate the document.body
$oDocBody.innerhtml=$procList


$oDocBody.style.font=”12pt Arial”;
$oIE.document.bgcolor=”#D7D7EA”


#Reading back from IE.
$oTBody=@($oIE.document.getElementsByTagName(“TBODY”))[0] ;
foreach ($oRow in $oTBody.childNodes)
{
   #check the 4 column(WS),and highlight it if it is greater than 5MB.
   $WS=(@($oRow.childNodes)[4].innerhtml) -as [int]  ;
   if (($ws -ne $null) -and ($WS -ge 5mb)) {
       $oRow.bgColor=”#AAAAAA” ;
   }
}


#Prepare a title.
$oTitle=$oIE.document.createElement(“P”)
$oTitle.style.font=”bold 20pt Arial”
$oTitle.innerhtml=”Process List”;
$oTitle.align=”center” ;


#Display the title before the Table object.
$oTable=@($oIE.document.getElementsByTagName(“TABLE”))[0] ;
$oDocBody.insertBefore($oTitle,$oTable) > $null;



Displaying the “$procList”  can also be accomplished with “write” methods instead of innerhtml assignment.  But we should perform some extra checks to determine  whether the document.body  is type of [mshtml.htmldocumentclass]. If the “htmlfile” progid has the following settings in the registry:



HKEY_CLASSES_ROOT\CLSID\{25336920-03F9-11CF-8FD0-00AA00686F13}\InProcServer32 


Class        : mshtml.HTMLDocumentClass
Assembly  : Microsoft.mshtml, Version=7.0.3300.0,  Culture=neutral,       PublicKeyToken=b03f5f7f11d50a3a



then, mshtml.htmldocumentclass become .NET wrapper for the document.body object.
So the following line :
$oDocBody.innerhtml=$procList


Can be replaced with:


If ($oIE.document.psbase.tostring() –eq “system.__comobject”) {
    $oIE.document.write([string]$proclist)
}
else {
    $oIE.document.IHTMLDOcument2_write([string]$proclist)
}
$oDocBody=$oIE.document.documentelement.lastchild ;


 


Yuksel Akinci [MSFT]
Windows PowerShell Team
Microsoft Corporation
This posting is provided “AS IS” with no warranties, and confers no rights.