首页 > 解决方案 > 批处理文件:在 FOR 循环中跳过以 _ 开头的文件夹

问题描述

我想排除所有以_开头的配置文件,而不必在排除文本文件中列出每个配置文件。

是否有可能做到这一点 ?

@echo off
set Target=D:\backup

        for /f "tokens=*" %%I in ('dir /a:d-h /b "%SystemDrive%\Users\*"') do if exist "%Target%\%%~nXI\" (

    ........

)

pause
exit

非常感谢您的帮助!

标签: windowsfor-loopbatch-filetokendelimiter

解决方案


以下代码示例提供了一种用于检索您需要的配置文件名称(不是特殊帐户且名称不以下划线开头的名称)及其当前配置文件路径的方法。

@For /F "Skip=1Tokens=1,2" %%G In ('%__AppDir__%wbem\WMIC.exe UserAccount Where^
 "LocalAccount='True' And Not Name Like '[_]%%'" Get Name^,SID 2^>Nul'
)Do @For /F %%I In ("%%H")Do @For /F "Tokens=2Delims==" %%J In ('
 %__AppDir__%wbem\WMIC.exe Path Win32_UserProfile Where^
 "SID='%%I' And Special!='True'" Get LocalPath /Value 2^>Nul'
)Do @For /F "Tokens=*" %%K In ("%%J")Do @Echo User name:"%%G",Profile path:"%%K"
@Pause

虽然上述内容并不能直接帮助您完成任务,但可以非常简单地对其进行调整。(如果您在配置文件路径和目标目录之间复制/移动对象,它甚至还为您提供了使用的机会%%K。) :

@Set "Target=D:\backup"
@For /F "Skip=1Tokens=1,2" %%G In ('%__AppDir__%wbem\WMIC.exe UserAccount Where^
 "LocalAccount='True' And Not Name Like '[_]%%'" Get Name^,SID 2^>Nul'
)Do @For /F %%I In ("%%H")Do @For /F "Tokens=2Delims==" %%J In ('
 %__AppDir__%wbem\WMIC.exe Path Win32_UserProfile Where^
 "SID='%%I' And Special!='True'" Get LocalPath /Value 2^>Nul'
)Do @For /F "Tokens=*" %%K In ("%%J")Do @If Exist "%Target%\%%G\" (
    Rem …your code here
)
@Pause


如果您的用户名有可能包含空格,那么答案就会变得更加复杂。如果您确实在不是 Windows 7 的系统上运行它,它可以更简单地完成,但无论您使用哪种支持的操作系统,它都应该工作。

@Set "Target=D:\backup"
@For /F Tokens^=4Delims^=^" %%G In ('%__AppDir__%wbem\WMIC.exe UserAccount^
 Where "LocalAccount='TRUE' And Not Name Like '[_]%%'" Assoc:List^
 /ResultRole:SID 2^>NUL')Do @For /F Tokens^=1* %%H In (
 '%__AppDir__%wbem\WMIC.exe UserAccount Where "Name='%%G'" Get SID^
 /Value 2^>NUL^|%__AppDir__%find.exe "="')Do @For %%I In (%%H
)Do @For /F "Tokens=1*Delims==" %%J In ( 
 '%__AppDir__%wbem\WMIC.exe Path Win32_UserProfile Where^
 "SID='%%I' And Special!='TRUE' And LocalPath Is Not Null" Get LocalPath /Value^
 2^>NUL^|%__AppDir__%find.exe "="')Do @For /F "Tokens=*" %%L In ("%%K"
)Do @If Exist "%Target%\%%G\" (
    Rem …your code here
)
@Pause

在此示例中,您的用户配置文件路径将分配给%%~L,(%%K与前面示例中的 , 相反)。


推荐阅读