3

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 3

5

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()}}
Sign up to request clarification or add additional context in comments.

3 Comments

I must be doing something wrong . Doesn't seem to work when i tried using Fullname.
$excel = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application") $excel.DisplayAlerts = $false $excel.Workbooks | %{if($_.FullName -imatch "M:\Items.xlsx"){$_.Close()}}
@drdrdr -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"
2

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

1 Comment

This way Works. But do you have a way of not triggering document recovery when opening the excel file again
0
$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

1 Comment

Why is it always messing up my formating xD and removing the first line I write...

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.