title: Powershell, close Excel
body: <p>I have the following code and it works perfectly except it's not closing Excel properly. It's leaving an Excel process running.</p>
  <p>Is there a way to close Excel properly without killing the process?</p>
  <p>Since i'm using other Excel files while running this script i can not kill all active Excel processes.</p>
  <p>I think i tried everything i found online.</p>
  <pre><code>$WorkDir = &quot;D:\Test\QR_ES\RG_Temp&quot;
  $BGDir = &quot;D:\Test\QR_ES\3_BG&quot;
  $File = &quot;D:\Test\QR_ES\4_Adr_Excel\KD_eMail.xlsx&quot;
  $SentDir = &quot;D:\Test\QR_ES\RG_Temp\Sent\Dunning&quot;
  
  chdir $WorkDir
  
  $firstPageList = Get-ChildItem &quot;$WorkDir\1*.pdf&quot; -File -Name
  
  ForEach ($firstPage in $firstPageList)
  {
  $secondPage = &quot;$BGDir\BG_RG.pdf&quot;
  
  $output = &quot;Dunn-$firstPage&quot;
  
  invoke-command {pdftk $firstPage background $secondPage output $output}}
  
  del 1*.pdf
  
  gci $WorkDir\Dunn-*.pdf | rename-item -newname {$_.Name.Substring(5)} -Force
  
  
  $Excel = New-Object -ComObject Excel.Application
  $Excel.visible = $false
  $Workbook = $Excel.workbooks.open($file)
  
  $DunnList = Get-ChildItem &quot;$WorkDir\1*.pdf&quot; -File -Name
  
  ForEach ($Dunn in $DunnList)
  {
  $Worksheets = $Workbooks.worksheets
  $Worksheet = $Workbook.Worksheets.Item(&quot;KD_eMail&quot;)
  $Range = $Worksheet.Range(&quot;A1&quot;).EntireColumn
  $DunnSearch = $Dunn.Substring(0,5)
  $SearchString = $DunnSearch
  $Search = $Range.find($SearchString)
  $Recipient = $Worksheet.Cells.Item($Search.Row, $Search.Column + 1)
  
  $Msg = &quot;&lt;span style='font-family:Calibri;font-size:12pt;'&gt;Test&lt;/span&gt;&quot;
  
  $Outlook = New-Object -ComObject Outlook.Application
  $namespace = $Outlook.GetNameSpace(&quot;MAPI&quot;)
  $namespace.Logon($null, $null, $false, $true)
  $EmailFrom = ('test@test.com')
  $account = $outlook.Session.Accounts.Item($EmailFrom)
  $Mail = $Outlook.CreateItem(0)
  $Mail.HTMLBody = $Msg
  $Mail.Subject = &quot;OP - $SearchString&quot;
  
  $Mail.To = $Recipient
  
  function Invoke-SetProperty {
      param(
          [__ComObject] $Object,
          [String] $Property,
          $Value        
      )
      [Void] $Object.GetType().InvokeMember($Property,&quot;SetProperty&quot;,$NULL,$Object,$Value)
     }
  Invoke-SetProperty -Object $mail -Property &quot;SendUsingAccount&quot; -Value $account
  
  $Mail.Attachments.Add(&quot;$WorkDir\$Dunn&quot;)
  $Mail.Save()
  $Mail.close(1)
  $Mail.Send()}}
  
  $workbook.close($false)
  
  $Excel.Quit()
  
  chdir $WorkDir
  
  del 1*.pdf
  </code></pre>