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

时间:2015-06-30 15:30:52

标签: excel powershell

我在完成此PowerShell脚本后尝试删除任务管理器中的进程,但在脚本运行后仍会显示。有什么想法吗?

    #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的东西来清除这个过程。

1 个答案:

答案 0 :(得分:1)

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

$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()

之前