I am trying to execute a powershell command using my program to close windows explorer window based on selection. It seems to be executed correctly, but the window does not close. Can anyone help me to resolve this issue?
Here is the command: to close windows explorer window which selected C drive.
powershell.exe (((((New-Object -ComObject Shell.Application).Windows()) ^| Where-Object { $_.LocationURL -like '$(([uri]"C:\").AbsoluteUri)*' })) ^| ForEach-Object { $_.Quit() })
This seemed to work for me:
$ShellApplication = New-Object -ComObject Shell.Application
$ShellApplication.Windows() | Where-Object{$_.Name -eq "File Explorer" -and $_.LocationURL -match "General_logs" } | ForeEach-Object{ $_.Quit() }
Obviously you'll need to change what you're matching. I haven't messed with it much, we can probably make this more eloquent.
In one line:
(New-Object -ComObject Shell.Application).Windows() | Where-Object{$_.Name -eq "File Explorer" -and $_.LocationURL -match "General_logs" } | ForEach-Object{ $_.Quit() }
Now if you want to run from PowerShell.exe :
powershell -NoProfile -WindowStyle Hidden -command .{ (New-Object -ComObject Shell.Application).Windows() | Where-Object{$_.Name -eq 'File Explorer' -and $_.LocationURL -match 'General_logs' } | ForEach-Object{ $_.Quit() } }
This worked for me but note I had to change the quoting. It's a bad habit of mine to double quote when it isn't needed. I also added -WindowStyle Hidden so you don't get the flash of the console and -NoProfile, so you don't have to wait for the profile script to run...