none
Powershell script freezes randomly within ForEach-Object loop

    Question

  • Dear Community,

    to manage our Outlook signatures I'm using a Powershell script. It's working fine with one exception, swapping our company logo.
    The script copies the logo to every persons signature folder (about 390), searches for the corresponding htm files,  replaces the logos dimension within the html file, opens the html file within word and exports it to rtf.

    All of this works, but the script freezes randomly. Sometimes after 180 iterations another time after 50 iterations and I have no idea where this comes from or how to debug.

    I'd be glad if someone could take a look at my code and give me a hint how to improve or debug the script.

    $sigfiles = Get-ChildItem -Recurse -File  -Include *.htm $folder
    $sigfiles | % {
    	(Get-Content $_) -replace "width=[0-9]+", "width=$($dim.width)" `
    					 -replace "height=[0-9]+", "height=$($dim.height)" `
    					 -replace ";height:[0-9]+((\.)[0-9]+)?pt", ";height:$(($dim.Height * 0.75) -replace ",",".")pt" `
    					 -replace "width:[0-9]+((\.)[0-9]+)?pt", "width:$(($dim.Width * 0.75) -replace ",",".")pt" | Out-File $_
    	$wordobj = New-Object -ComObject Word.Application
    	$wordobj.Visible = $false
    	$worddoc = $wordobj.Documents.Open($_.FullName)
    	$opt = 6
    	$name = $_.FullName -replace "\.htm",".rtf"
    	$wordobj.ActiveDocument.SaveAs($name,$opt)
    	$wordobj.Quit()
    }

    Thank you in advance!
    Marc

    Thursday, June 14, 2018 7:54 AM

Answers

  • If you keep recreating the Word object you will exceed system limits. Only create the word object once outside of the loop.  Always release all COM objects you have created.


    \_(ツ)_/

    • Marked as answer by Marc.Sam Thursday, June 14, 2018 9:01 AM
    Thursday, June 14, 2018 7:58 AM
    Moderator

All replies

  • If you keep recreating the Word object you will exceed system limits. Only create the word object once outside of the loop.  Always release all COM objects you have created.


    \_(ツ)_/

    • Marked as answer by Marc.Sam Thursday, June 14, 2018 9:01 AM
    Thursday, June 14, 2018 7:58 AM
    Moderator
  • Just tested my script with your improvements and it's not only working its way faster.

    To release the COM Object I found this Scripting Guy blog article:

    https://blogs.technet.microsoft.com/heyscriptingguy/2015/02/20/powertip-release-com-object-in-powershell/
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null

    I think theres a lot to learn for me in working with COM objects. If anyone has a suggestion on a ressource where I could learn about COM objects I would be thankful.

    Thank you!

    Marc

    Thursday, June 14, 2018 9:01 AM