I am stuck on how to completely quit Excel when working with files in Powershell. I have a find and replace script that searches through workbooks and sheets, once completed, I notice that there is still a single process running in task manager as shown from image below:
Here is the script:
Function Get-ExcelFunction () {
$rootDir = Get-ChildItem $dirPath -Filter *.xlsx -Recurse
ForEach ($dir in $rootDir) {
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Workbook = $Excel.workbooks.open($dir.FullName)
ForEach ($sheet in $Workbook.Worksheets) {
$Range = $sheet.Range("A1:EZ800").EntireColumn #Range of Cells to look at
$Search = $Range.find($oldString)
if ($null -ne $Search) {
$FirstAddress = $search.Address
do {
$Search.value() = $Search.value().Replace($oldString, $newString) #String to Update
$Search = $Range.FindNext($Search)
} while ( $null -ne $Search -and $Search.Address -ne $FirstAddress)
$sheetName = $sheet.Name #Grab the name of the sheet that is being updated
(Join-Path $dir.Directory $dir.BaseName) + "($sheetName)" + $dir.Extension >> $filePathName #Write the path to where the file was changed to a change log file
}
}
$Workbook.Save()
$Workbook.Close()
$Excel.quit()
# Relinquish references to *all* Excel objects.
Remove-Variable -Name Excel, Workbook, sheet
# With all references released, running the garbage collector
# should now release the COM objects and terminate Excel
# shortly after.
[GC]::Collect()
}
Prior to adding:
Remove-Variable -Name Excel, Workbook, sheet
[GC]::Collect()
I would have multiple processes still remaining, so I am wondering why my code is not completing all the Excel processes?