代码之家  ›  专栏  ›  技术社区  ›  Eric Fortin

批处理文件中文件属性的测试

  •  9
  • Eric Fortin  · 技术社区  · 16 年前

    我正在写一个批处理文件,我需要知道一个文件是否是只读的。我该怎么做?

    2 回复  |  直到 16 年前
        1
  •  13
  •   Patrick Cuff    16 年前

    像这样的方法应该会奏效:

    @echo OFF
    
    SETLOCAL enableextensions enabledelayedexpansion
    
    set INPUT=test*
    
    for %%F in (%INPUT%) do (
        set ATTRIBS=%%~aF
        set CURR_FILE=%%~nxF
        set READ_ATTRIB=!ATTRIBS:~1,1!
    
        @echo File: !CURR_FILE!
        @echo Attributes: !ATTRIBS!
        @echo Read attribute set to: !READ_ATTRIB!
    
        if !READ_ATTRIB!==- (
            @echo !CURR_FILE! is read-write
        ) else (
            @echo !CURR_FILE! is read only
        )
    
        @echo.
    )
    

    当我运行此命令时,会得到以下输出:

    File: test.bat
    Attributes: --a------
    Read attribute set to: -
    test.bat is read-write
    
    File: test.sql
    Attributes: -ra------
    Read attribute set to: r
    test.sql is read only
    
    File: test.vbs
    Attributes: --a------
    Read attribute set to: -
    test.vbs is read-write
    
    File: teststring.txt
    Attributes: --a------
    Read attribute set to: -
    teststring.txt is read-write
    
        2
  •  7
  •   Community Mohan Dere    8 年前

    要测试特定文件,请执行以下操作:

    dir /ar yourFile.ext >nul 2>nul && echo file is read only || echo file is NOT read only
    

    dir /ar *
    

    获取读/写文件列表的步骤

    dir /a-r *
    

    要列出所有文件并报告是只读还是读/写:

    for %%F in (*) do dir /ar "%%F" >nul 2>nul && echo Read Only:  %%F|| echo Read/Write: %%F
    

    编辑

    Patrick's answer 如果文件名包含,则失败 ! . 这可以通过在循环中打开和关闭延迟扩展来解决,但是还有另一种方法来探测延迟扩展 %%~aF 值,而不诉诸延迟扩展,甚至不借助环境变量:

    for %%F in (*) do for /f "tokens=1,2 delims=a" %%A in ("%%~aF") do (
      if "%%B" equ "" (
        echo "%%F" is NOT read only
      ) else (
        echo "%%F" is read only
      )
    )
    
    推荐文章