38

你好我正在寻找一个批处理文件来检查给定文件夹中是否有任何类型的文件。

到目前为止,我已经尝试了以下

if EXIST FOLDERNAME\\*.* ( echo Files Exist ) ELSE ( echo "Empty" ) 

如果我知道文件扩展名(例如带有以下内容的 txt 文件),我可以让它工作

if EXIST FOLDERNAME\\*.txt ( echo Files Exist ) ELSE ( echo "Empty" )

谢谢您的帮助

4

4 回答 4

54

检查文件夹是否至少包含一个文件

>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)

检查文件夹或其任何后代是否包含至少一个文件

>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)

检查一个文件夹是否至少包含一个文件或文件夹。
注意添加/a选项以启用隐藏和系统文件/文件夹的查找。

dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)

检查一个文件夹是否至少包含一个文件夹

dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)
于 2012-05-30T14:57:10.227 回答
12

对于目录中的文件,您可以使用以下内容:

if exist *.csv echo "csv file found"

或者

if not exist *.csv goto nofile
于 2015-12-15T10:06:08.217 回答
7

你可以用这个

@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)
echo Folder is empty or does not exist

取自这里

那应该做你需要的。

于 2012-05-30T10:03:04.797 回答
0

一个滚动你自己的功能。

是否支持递归与2nd开关。

此外,允许;接受的答案无法解决的文件名称虽然是一个很好的答案,但这将解决这个问题。

这个想法来自https://ss64.com/nt/empty.html

代码中的注释。

@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written:               2020.01.26
:: Posted on the thread here:   https://stackoverflow.com/q/10813943/8262102
:: Based on:                    https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>"   = Your path wrapped in quotes.
:: <BOOLEAN>  = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE      = if directory doesn't exist.
:: 0-inf      = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
  echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
  ) else if not "%~1"=="" (
  set count=0 & set msg= & set dirExists=
  if not exist "!%~1!" (set msg=FALSE)
  if exist "!%~1!" (
   if {%~2}=={TRUE} (
    >nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
    set msg=!count!
    )
   if {%~2}=={FALSE} (
    for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
    set msg=!count!
    )
   )
  )
  set "%~1=!msg!" & goto :eof
  )
于 2020-01-26T13:39:50.877 回答