Close specific Excel file using Powershell

Viewed 2592

What would be the appropriate PowerShell cmdlet to use to kill a specific Excel file. The command

Stop-Process -Name "excel"

closes all open Excel applications.

Thanks in advance!

3 Answers

Actually, excel opens .xlsx files in one instance of excel.exe

Kill the excel.exe will kill all opening workbooks. The MainWindowTitle only shows the active workbook, so you will not able to match passive workbooks by the property.

A better way to close a specific workbook is to acquire the excel instance by com object.

Close the workbook matched the Name (file name) or FullName (file path)

$excel = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application")
$excel.DisplayAlerts = $false
$excel.Workbooks | %{if($_.Name -imatch "excel file name"){$_.Close()}}

Try this out:

Get-Process excel –ea 0 | Where-Object { $_.MainWindowTitle –like ‘*report.csv*’ } | Stop-Process

Here's the official guide from MS:

Stop-Process

$Application = New-Object -ComObject excel.application
$Application.Visible=$True

$workbook = $application.Workbooks.open("C:\mySheet.xlsx")

Start-Sleep -Seconds 5

$workbook.close($false)

The problem is that the window remains open while the dokument is closed.

Hope it still helps. BR

Related