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.