Batch to delete all files in a folder with a wildcard in the path

佐手、 提交于 2019-12-06 14:49:16

问题


So what I'm trying to do is go into every folder in the following directory

"C:\Documents and Settings\"

and for every folder in it, regardless of the name, check if this path exists

"C:\Documents and Settings\*\Local Settings\Application Data\CSMRpt\"

if it exists then delete all txt files inside that director, if the path doesn't exists then do nothing and move on to the next folder inside "C:\Documents and Settings\"

This is what I came up with so far:

set PATH = "\Local Settings\Application Data\CSMRpt\"
set FILETYPE = "*.txt"
for /d %%g in ("C:\Documents and Settings\*") do if exist %%g%PATH% goto pathexists
:pathexists
del %%g%PATH%%FILETYPE%

回答1:


Try this.

@echo off
setlocal
set cwd=%CD%
set p=Local Settings\Application Data\CSMRpt
cd /d "c:\Documents and Settings\"
for /d %%I in (*) do (
    if exist "%%I\%p%\" (
        pushd "%%I\%p%\"
        del /q *.txt
        popd
    )
)
:: (change back to original directory)
cd /d "%cwd%"



回答2:


A couple things wrong here, you can't have spaces around the = in the set command, using goto wouldn't have passed the variable (you could however use call instead and pass it as a argument) you don't need quotes around every variable, %PATH% although you can reset it, you shouldn't for something like this as it is a environment variable.

Corrected code:

set THEPATH=\Local Settings\Application Data\CSMRpt\
set FILETYPE=*.txt
for /d %%g in ("C:\Documents and Settings\*") do if exist "%%g%THEPATH%." del "%%g%THEPATH%%FILETYPE%"

If you really didn't want the for loop to be one line you could do this as well

set THEPATH=\Local Settings\Application Data\CSMRpt\
set FILETYPE=*.txt
for /d %%g in ("C:\Documents and Settings\*") do if exist "%%g%THEPATH%." call :deltxtfiles "%%~g"

exit /B

:deltxtfiles
del "%~1%THEPATH%%FILETYPE%"
goto:eof


来源:https://stackoverflow.com/questions/15028358/batch-to-delete-all-files-in-a-folder-with-a-wildcard-in-the-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!