Search code examples
javascriptpowershellinternet-explorerwindows-serverwindows-server-2016

Using PowerShell to run Javascript in Internet Explorer on Windows Server


I have this piece of a PowerShell script:

$IE = New-Object -com InternetExplorer.Application
$IE.Navigate($URL)
While ($IE.ReadyState -Ne 4) {Start-Sleep -Milliseconds 100}
$IE.Document.ParentWindow.ExecScript("var JSIEVariable = new XMLSerializer().serializeToString(document);", "javascript")
$Obj = $IE.Document.ParentWindow.GetType().InvokeMember("JSIEVariable", 4096, 
$Null, $IE.Document.parentWindow, $Null)
$HTML = $Obj.ToString()
$IE.Quit()

On Windows 10 it works fine but on Windows Server 2016 for lines 4, 5 and 6 I get the error:

You cannot call a method on a null-valued expression.

I'm pretty sure it has something to do with extra security in Windows Server preventing IE from running Javascript. There must be some way to dial back that security to be more on par with Windows 10 so that this script can run properly, but I can't figure out how. I've turned off IE Enhanced Security Configuration and ensured that Active Scripting is enabled. Aside from that I don't know what else to do.


Solution

  • A coworker helped me figure this out. It doesn't have anything to do with IE security, at least not as far as anything that hasn't already been covered. The problem is 'Microsoft.mshtml.dll' is missing from the GAC. It won't be present on a clean install of Windows Server but installing something like Office or Visual Studio will add it. However, i would bet that most people running a Windows Server wouldn't want to do that just for the sake of getting this working. What I did was copy the following folder/file structure from my Windows 10 PC to my server, closed out all instances of PowerShell and ISE and when I opened PowerShell again and ran the script everything worked.

    C:\Windows\assembly\GAC\Microsoft.mshtml C:\Windows\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a C:\Windows\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a\Microsoft.mshtml.dll C:\Windows\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a__AssemblyInfo__.ini