title: How to cleanup $IE object, close current processes
body: <p>Is there a simple command to close the current IE COM Object as part of cleanup?</p>
  
  <p>First attempt, didn't work:</p>
  
  <pre><code>Try{
    $ErrorActionPreference = "Stop"
    $ie = New-Object -COMObject InternetExplorer.Application
    $ie.visible = $true
    $ie.navigate("www.site.com")
    # do other stuff
  
  }
  Catch{
    write-host “Exception Message: $($_.Exception.Message)” -ForegroundColor Red
  
  } 
  
  Finally{
    $ie.Quit() # $ie does not have method Quit()
  }
  </code></pre>
  
  <p>Also tried the following:</p>
  
  <pre><code>Catch{
      Get-Process iexplore | ? {$PID -eq $_.Id} | Stop-Process
  }
  </code></pre>
  
  <p>Nothing I do seems to work. All I wish to do is close down the $ie object from the current script. There may be other IE processes running simultaneously, therefore I only want to close the one I just worked with. Any ideas?</p>
  
  <p>Edit: Why is $ie no longer usable by the time the script reaches the Finally{} ? This is not answered in the post you referenced as a duplicate.</p>
  
  <p><strong>Solved, kinda..but not really</strong></p>
  
  <pre><code>$ie = New-Object -COMObject InternetExplorer.Application
  $currentIDs = (Get-Process iexplore).Id # how do I only get process IDs of current script?
  
      Try{
      $ErrorActionPreference = "Stop"
  
          ... more code ...
  
      $ie.visible = $true
      $ie.navigate("http://www.allregs.com/tpl/Main.aspx")
  
          ... more code ...
      }
  
      Catch{
      write-host “Exception Message: $($_.Exception.Message)” -ForegroundColor Red
      Write-Host "Failed." -ForegroundColor Red 
  }
  
      Finally{
      Get-Process | ? {($_.ProcessName -eq 'iexplore') -and ($_.Id -in $currentIDs )} | Stop-Process
  }
  </code></pre>
  
  <p>This works and closes any IE processes. The issue is that I think this will also close all other IE processes that may be running simultaneously. Can anyone confirm this? And if so, if there's is there a way to only close the current IE processes of this script? </p>