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

时间:2009-05-20 14:27:47

标签: batch-file file-attributes

我正在编写批处理文件,我需要知道文件是否只读。我怎么能这样做?

我知道如何使用%~a修饰符来获取它们,但我不知道如何处理此输出。它给出了类似-ra ------的东西。如何在批处理文件中解析它?

2 个答案:

答案 0 :(得分:13)

这样的事情应该有效:

@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

答案 1 :(得分:7)

测试特定文件:

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
  )
)