0

How do I check if an explorer window is open or not in batch?

I need to take a screenshot of the directory with a file selected, but only after the window has opened. The window title is always the same.

Example:

REM Opening folder with a file selected
START /W EXPLORER /SELECT,\\10.10.10.10\C$\ThisFolder\FileToHighlight.txt
REM Unreliably waiting for window to open
TIMEOUT /T 3 /NOBREAK >NUL
REM Taking screenshot of window with a third-party app
START .\Bin\screenshot-cmd.exe -wt "ThisFolder" -o .\Screenshots\%var%.png
phuclv
  • 37,963
  • 15
  • 156
  • 475
ellm62
  • 33
  • 7

2 Answers2

1

Provided there can be no other window with the same title as the opened folder you can use tasklist:

@echo off
rem DON'T ADD A TRAILING \ IN THE PATH!
set folder=d:\path\foldername
explorer "%folder%"
:wait
    timeout 1 >nul
    for %%z in ("%folder%") do (
        tasklist /fi "windowtitle eq %%~nxz" /fi "imagename eq explorer.exe" ^
        | find "explorer.exe" >nul
        if errorlevel 1 goto wait
    )
pause
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Thanks for the reply. A stipulation is that I need to have a file selected for the screenshot, so I'm using EXPLORER /SELECT,%folder% %folder% is something like "D:\Folder\FileWithInFolder.txt" Could this be causing your loop not to work for me? It doesn't make it to the pause. – ellm62 Sep 29 '15 at 13:34
  • Of course, since the code extracts a FOLDER name, not the FILE name. See [Get parent directory name for a particular file using DOS Batch scripting](http://stackoverflow.com/q/2396003) – wOxxOm Sep 29 '15 at 13:40
0

It's very easy to check if an explorer window is opened with Scriptable Shell Objects which is 100% reliable, unlike solutions using tasklist which sometimes may not work because the current folder path isn't available in the task information. Here's a PowerShell script that checks whether the folder has been opened or not, and sleep for 1 second if it isn't opened

$path = '\\10.10.10.10\C$\ThisFolder\FileToHighlight.txt'
$shell = New-Object -ComObject Shell.Application
do {
    sleep 1
    $window = $shell.Windows() | where { $_.LocationURL -ieq ([uri]$path).AbsoluteUri }
} while ($window -eq $null) # wait until the folder is opened

# Explorer window has opened, take the screenshot
start .\Bin\screenshot-cmd.exe -wt "ThisFolder" -o ".\Screenshots\$var.png"

Alternatively you can change $_.LocationURL -ieq ([uri]$path).AbsoluteUri to

$_.Document.Folder.Self.Path -ieq $path

You can also use VBS or Jscript if you like. Check my link above to see the equivalent version in Jscript, and even a hybrid batch-Jscript solution

phuclv
  • 37,963
  • 15
  • 156
  • 475