Close Explorer window by varying ID or filename


I’ve been scouring these forums for hours trying to figure out a way to code something that I thought would be much more simple than this.

So here’s what I’m trying to do:
My task scheduler runs a script every two days. The script opens an explorer.exe path to a folder, and then deletes all of the files in that folder. The scheduler runs the script at night while I’m not in office. However, when I get into the office, the explorer window is open to that page. Trivial, I know – but i don’t want to see that window open, so I want the script to run, and then close the window, so I don’t see anything.

I’ve tried this every which way. When I try to do something simple like


but when I do that, I get an error message saying that the variable is null.

Then I tried stopping the process. But I don’t want all explorer files to close, just that particular explorer window to close. So in order to do that, I have to know the ID of the window. But since the ID of that particular window is not static, I need to get the process ID – assign it to a variable – then use the stop-process cmdlet using the variable.

This is what I’m trying now:

However, when I run this script, it’s still saying that the variable is null.

So how do I assign a value to a variable? Or if anyone has a better way of closing a specific window.

(I’ve tried using the stop-process using just the mainwindowtitle – but it still wants an id)


If you really want to close a specific File Explorer window, then you would need to use Shell.Application. List opens file explorer windows:

I want to close the one in c:\path\folde, so lets find it and close it:

However as mentioned in the comments, you’re overcomplicating this. The point of PowerShell is to automate it, which usually means you don’t want to use a GUI at all. I’m not sure what you want to remove or keep etc. but here’s a sample you can work with:


Close Explorer window by varying ID or filename by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply