【问题标题】:Batch file : skipping folders starting with _ in FOR loop批处理文件:在 FOR 循环中跳过以 _ 开头的文件夹
【发布时间】:2020-04-24 12:46:11
【问题描述】:

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

这样可以吗?

@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

非常感谢您的帮助!

【问题讨论】:

  • 使用 FOR 命令行 for /F "delims=" %%I in ('dir /A:D-H /B "%HomeDrive%\Users\*" 2^>nul ^| %SystemRoot%\System32\findstr.exe /B /L /V "_"') do if exist "%Target%\%%I\" ( 排除带有用户配置文件(主目录)的驱动器上以下划线开头的用户配置文件目录。注意:%SystemDrive%%HomeDrive% 通常会扩展为相同的字符串,但 %HomeDrive% 是此任务的正确变量。
  • 绝对不能保证所有本地配置文件都可以在%systemdrive%%homedrive% 上找到,更不用说在名为Users 的目录中了。此外,不能保证保存配置文件的目录名称与用户配置文件名称匹配。

标签: windows for-loop batch-file token delimiter


【解决方案1】:

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

@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 相对)。

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多