Testing for file attribute in batch file

南楼画角 提交于 2019-11-30 13:05:12

Something like this should work:

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

When I run this I get the following output:

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
dbenham

To test a specific file:

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

To get a list of read only files

dir /ar *

To get a list of read/write files

dir /a-r *

To list all files and report whether read only or read/write:

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

EDIT

Patrick's answer fails if the file name contains !. This can be solved by toggling delayed expansion on and off within the loop, but there is another way to probe the %%~aF value without resorting to delayed expansion, or even an environment variable:

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
  )
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!