2009-05-20 30 views
9

我在写一个批处理文件,我需要知道文件是否只读。我怎样才能做到这一点 ?测试批处理文件中的文件属性

我知道如何让它们使用%〜a修饰符,但我不知道该如何处理这个输出。它提供了类似-ra ------的东西。我怎样才能解析这个批处理文件?

+0

什么样的批处理文件? bash,DOS ...? – 2009-05-20 14:39:05

+0

Windows批处理文件,你可以从他看到提及%〜a。 – Joey 2009-05-20 17:47:53

回答

12

像这样的东西应该工作:

@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 
5

要测试一个特定的文件:

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