2009-05-20 54 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 
) 
)