How can I set a variable in Batch after an "if exists" check?

How can I set a variable in Batch after an "if exists" check?

@ECHO OFF
setlocal enabledelayedexpansion
if exist ('dir c* /B /A:-D') set Lo=C
echo Lo: !Lo!
pause

I expect the results to say "Lo: C" rather than currently just "Lo:" when I have a file starting with C in the folder.

1

1 Answer

The only way to directly process the output of another cmd is using for /f

@ECHO OFF
if exist "X:\Path\c*" (set "Lo=C") else (set "LO=n/a")
echo Lo: %Lo%
pause

To asure it's not a directory

@ECHO OFF
Set "LO=n/a"
for /f "delims=" %%A in ('dir /B /A-D "X:\Path\C*" 2^>NUL') Do set "Lo=C"
echo Lo: %Lo%
pause

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like