Domanda

Sto scrivendo un file batch e ho bisogno di sapere se un file è di sola lettura. Come posso fare?

So come ottenere utilizzando il% ~ un modificatore, ma non so cosa fare con questa uscita. Dà qualcosa come -RA ------. Come posso analizzare questo file batch?

È stato utile?

Soluzione

Qualcosa del genere dovrebbe funzionare:

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

Quando ho eseguito questo ottengo il seguente 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

Altri suggerimenti

Per testare un file specifico:

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

Per ottenere un elenco dei file di sola lettura

dir /ar *

Per ottenere un elenco dei file di lettura / scrittura

dir /a-r *

Per elencare tutti i file e riferire se di sola lettura o lettura / scrittura:

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

Modifica

di Patrick risposta non riesce se il nome del file contiene !. Questo può essere risolto commutando espansione ritardata e disattivare all'interno del ciclo, ma c'è un altro modo per sondare il valore %%~aF senza ricorrere all'espansione ritardo, o anche una variabile di ambiente:

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
  )
)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top