Wednesday, January 26, 2011

Create MHT from HTML in Powershell

$adSaveCreateNotExist = 1
$adSaveCreateOverWrite = 2
$adTypeBinary = 1
$adTypeText = 2

function SaveFileTo($msg,$mhtp){
$strm=New-Object -ComObject ADODB.Stream
$Strm.Type = $adTypeText
$Strm.Charset = "US-ASCII"
$Strm.Open()
$dsk=$msg.DataSource
$Dsk.SaveToObject($Strm, "_Stream")

$strm.SaveToFile($mhtp,$adSaveCreateOverWrite)
}

function createMHT($htmlPath,$mhtPath){

$objMessage= New-Object -ComObject CDO.Message
$objMessage.CreateMHTMLBody($htmlPath)
SaveFileTo $objMessage $mhtPath
}


createMHT "C:\Users\user\Desktop\sampleHtml\free small games.htm" "C:\Users\user\Desktop\sampleHtml\free small games.mht"

1 comment:

Robert said...

This works; however, the function leaves the html file locked. I have tried several things to remove the lock from the function without success. These include adding the following to the end of the respective functions:
$Strm.close()
Remove-Variable $Dsk
Remove-Variable $objMessage

Using the SysInternals handle utility, I have verified the powershell has a lock on the html file. There should be some way of clearing the lock. Have you found a way to close the handle on the file programatically through powershell?

Node.JS rest api Tutorials