0

I'm trying to delete the processes in task manager after I finish this powershell script, but it still appears after the script is run. Any ideas?

    #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

You can see at the end I run the ReleaseComObject stuff to clear the process.

1
  • Probably clean the objects in reverse order, that is, worksheet first, workbook second, application last. Commented Jun 30, 2015 at 16:18

1 Answer 1

2

it's really annoying i know, one way is:

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

If it still there, this is the killer way :)

$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

this one goes before the $excelObj.Quit()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.