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!
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()}}
-imatch operator is a regular expression, if you not familiar with it, you can easily change -imatch to -like. e.g. $_.FullName -like "M:\Items.xlsx" or even -eq "M:\Items.xlsx"Try this out:
Get-Process excel –ea 0 | Where-Object { $_.MainWindowTitle –like ‘*report.csv*’ } | Stop-Process
Here's the official guide from MS:
$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