Question:
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
1 2 3 |
$var1 = invoke-item C:\path\file $var1.quit() |
or
1 2 |
$var1.close() |
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:
1 2 |
get-process | where-object {$_.MainWindowTitle -eq "filename"} | select -property id | $var2 |
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)
Answer:
If you really want to close a specific File Explorer window, then you would need to use Shell.Application
. List opens file explorer windows:
1 2 3 4 5 6 7 8 |
$shell = New-Object -ComObject Shell.Application $shell.Windows() | Format-Table Name, LocationName, LocationURL Name LocationName LocationURL ---- ------------ ----------- File Explorer Windows file:///C:/Windows File Explorer folder file:///C:/path/folder |
I want to close the one in
c:\path\folde
, so lets find it and close it:
1 2 3 4 |
$shell = New-Object -ComObject Shell.Application $window = $shell.Windows() | Where-Object { $_.LocationURL -like "$(([uri]"c:\path\folder").AbsoluteUri)*" } $window | ForEach-Object { $_.Quit() } |
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:
1 2 3 4 5 6 7 |
#Get contents of folder (not recursive) Get-ChildItem -Path 'c:\path\folder' | #Only files Where-Object { !$_.PSIsContainer } | #Remove... Remove-Item |