在excel Powershell脚本运行后删除进程。 我错过了什么?

我试图在完成这个PowerShell脚本后删除任务pipe理器中的进程,但它仍然出现在脚本运行后。 有任何想法吗?

#Declarations $dir = "mydirectory*" $NewName = "mydirectory"+(Get-Date).ToString("yyyy.MM.dd")+".xlsx" $latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1 $latest.name $excelObj = New-Object -ComObject Excel.Application $excelObj.Visible = $False $excelObj.DisplayAlerts = $False $FileExists = Test-Path $NewName if($FileExists -eq $True) {#If todays file exists already Write-Host –NoNewLine "File Already Exists, Refreshing..." $workBook = $excelObj.Workbooks.Open($NewName) $Worksheet = $Workbook.WorkSheets.item("DataV2") $worksheet.activate() $workBook.RefreshAll() Start-Sleep -s 10 $workBook.Save() $excelObj.Quit() #delete old files (Get-ChildItem $dir -recurse | select -ExpandProperty fullname) -ne $NewName | remove-item } Else {#If todays file does not exist $workBook = $excelObj.Workbooks.Open($latest) $Worksheet = $Workbook.WorkSheets.item("DataV2") $worksheet.activate() $workBook.RefreshAll() Start-Sleep -s 10 $workBook.SaveAs($NewName) $excelObj.Quit() Start-Sleep -Seconds 10 #delete old files (Get-ChildItem $dir -recurse | select -ExpandProperty fullname) -ne $NewName | remove-item} #Remove Tasks and Prcesses [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelObj) [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workBook) Remove-Variable excelObj Remove-Variable workBook 

你可以看到在最后我运行ReleaseComObject的东西来清除进程。

我知道这真的很烦人,一种方法是:

 $workbook.Close() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) $excelObj.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelObj) Remove-Variable excelObj [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() 

如果它仍然存在,这是杀手的方式:)

 $excelObj.Visible = $true $ProcID = Get-Process | Where-Object {$_.MainWindowHandle -eq $excelObj.HWND} | Select -ExpandProperty ID $excelObj.Visible = $False Get-Process -Id $ProcID | Stop-Process -Force 

这个在$ excelObj.Quit()