简体   繁体   中英

Batch file to find files in a directory

I am creating a batch file to find if any files are present in the path d:\Users\gladiator\Desktop\my docs . If any files are present, I need to trigger an email stating which are the files present in that path.

This is the snippet of my batch script.

@echo off
for /f "delims=" %%F in ('dir /b /s "d:\Users\gladiator\Desktop\my docs"') do set MyVariable=%%F
echo %MyVariable%files are present

But this script is not displaying all the files present in that location.

Could someone help me to modify the script so as to display all the files present in the location?

Try to use setlocal enabledelayedexpansion to start a local environment before your loop, as described here:

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/setlocal

Then, after you're done, use endlocal

When you expand the variable MyVariable use !MyVariable! which is how "delayed expansion" within a local environment works (rather than %MyVariable% ).

Microsoft does not allow modification of an environment variable with set variable=... within a loop, without using "delayed expansion."

Here is an example with your code:

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%F in ('dir /b /s "d:\Users\gladiator\Desktop\my docs"') do (
  set MyVariable=%%F
  echo !MyVariable! file is present
)

endlocal

This will at least allow you to see the files present. Beyond that I'm not sure what you wish to do once filenames are detected.

If you want to fill MyVariable with all files found, then you can do this

@echo off
setlocal enabledelayedexpansion
set MyVariable=
for /f "delims=" %%F in ('dir /b /s "d:\Users\gladiator\Desktop\my docs"') do (
  set MyVariable=!MyVariable! %%F
)
echo !MyVariable! files found
endlocal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM