获取具有特定前缀的子目录

时间:2019-04-04 08:24:15

标签: batch-file cmd cycle prefix subdirectory

我正在创建简单的批处理脚本以删除特定应用程序的所有用户配置,但在最后一步尝试获取具有特定前缀的所有子文件夹时仍然失败...

这就是我现在拥有的:

@echo off
chcp 1250

SET appUserConfigDirectory=\AppData\Local\CompanyName
SET appConfigFolderPrefix=AppName.exe_Url

:: get parent folder of user folders
for %%d in (%USERPROFILE%) do SET userprofilesFolder=%%~dpd

SETLOCAL ENABLEDELAYEDEXPANSION
:: going through all user folders
for /F "delims=" %%d in ('dir %userprofilesFolder% /A:D-R-H-S /b') do (
    :: set full name of CompanyName folder in user AppData
    SET appConfigParentFolder=%userprofilesFolder%%%d%appUserConfigDirectory%
    IF EXIST !appConfigParentFolder! (
        :: There is a problem with dir command, it's says File not found even if subfolder with this prefix exists and print all subFolder no metter it's name...
        for /F "delims=" %%i in ('dir !appConfigParentFolder! /A:D /b %appConfigFolderPrefix%*') do (
        echo %%i)))

2 个答案:

答案 0 :(得分:1)

我找到了方法。带有前缀的正确dir命令应为:

dir !appConfigParentFolder!\%appConfigFolderPrefix%* /A:D /b

因此,此示例的完整版本为:

@echo off
chcp 1250

SET appUserConfigDirectory=\AppData\Local\CompanyName
SET appConfigFolderPrefix=AppName.exe_Url

for %%d in (%USERPROFILE%) do SET userprofilesFolder=%%~dpd

SETLOCAL ENABLEDELAYEDEXPANSION

for /F "delims=" %%d in ('dir %userprofilesFolder% /A:D-R-H-S /b') do (
    SET appConfigParentFolder=%userprofilesFolder%%%d%appUserConfigDirectory%
    IF EXIST !appConfigParentFolder! (
        for /F "delims=" %%i in ('dir !appConfigParentFolder!\%appConfigFolderPrefix%* /A:D /b') do echo %%i
    )
)

答案 1 :(得分:0)

请尝试以下操作:

forfiles /S /M !appConfigParentFolder! /C "cmd /c if @isdir==TRUE rmdir @path"

它将删除每个等于!appConfigParentFolder!的子目录。