How can I keep a batch file going until the opened folder window is closed?

66 views Asked by At

I've managed to run batch files using the /WAIT command which loads the program then stays running until a program is closed again. I want to do this but for a folder instead of a program, but when I run the following it closes upon loading the folder contents

start /WAIT explorer.exe "path/name/here"

Could anyone help with how I can alter this to keep the batch file running until I close the folder window?

1

There are 1 answers

1
Gerhard On

You can use a little help from PowerShell by creating a function inside of your batch-file. Yes, you can use PowerShell only, but I have no idea how much code your current script is and therefore not expecting you to re-write everything in PowerShell.

@echo off
set "fpath=d:\"

start "" "%fpath%"
call :runps

:try
for /F "delims=" %%i in ('powershell -file "%temp%\get_folders.ps1"') do (
    if /i "%%~i" == "%fp%" timeout /t 1 >null && goto :try
)

::Function
goto :EOF
:runps
echo $shell = New-Object -ComObject Shell.Application >"%temp%\get_folders.ps1"
echo $windows = $shell.Windows()>>"%temp%\get_folders.ps1"
echo foreach ($window in $windows) { >> "%temp%\get_folders.ps1"
echo    $fp = $window.Document.Folder.Self.Path >> "%temp%\get_folders.ps1"
echo    Write-Output "$fp" >>"%temp%\get_folders.ps1"
echo } >>"%temp%\get_folders.ps1"

The script will open the location you chose, then create the PowerShell script in your %temp% directory. The for loop will call the PowerShell script every 1 second.

The PowerShell script will loop through all open folders and simply print them. We catch the exact match using if in the batch script, if we find that it is still active, we keep on looping until it no longer finds the folder to be active.

Note, please create all other code above the ::Function label.