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
$var1 = invoke-item C:\path\file
$var1.quit()
or
$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:
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)
If you really want to close a specific File Explorer window, then you would need to use Shell.Application
. List opens file explorer windows:
$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:
$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:
#Get contents of folder (not recursive)
Get-ChildItem -Path 'c:\path\folder' |
#Only files
Where-Object { !$_.PSIsContainer } |
#Remove...
Remove-Item
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With