attrib
命令用于更改隐藏,系统,只读和存档等文件属性。
问题是您不能更改隐藏或系统文件的只读状态 - 无需另外清除或设置隐藏或系统状态。例如:
C:\somewhere>REM Set up a hidden test file.
C:\somewhere>echo foo > foo.txt
C:\somewhere>attrib +h foo.txt
C:\somewhere>REM Try to make the hidden test file read-only.
C:\somewhere>attrib +r foo.txt
Not resetting hidden file - C:\somewhere\foo.txt
C:\somewhere>REM We can make it read-only if we additionally clear the hidden status...
C:\somewhere>attrib -h +r foo.txt
C:\somewhere>REM (Revert that last change.)
C:\somewhere>attrib +h -r foo.txt
C:\somewhere>REM ...and we can make it read-only if we additionally make it hidden - which it already is.
C:\somewhere>attrib +h +r foo.txt
C:\somewhere>
(我假设系统属性的工作方式与上面相同,但我没有测试过。)
因此attrib
将用于此目的 - 但仅当批处理文件知道文件是否已隐藏或系统时,才能包含相应的+h
或+s
以及+r
。
最好的方法是什么?
答案 0 :(得分:0)
将隐藏和系统属性保存在变量中,清除并在需要时重新应用。
用法:
call :setAttr "+r -a" "file"
call :setAttr +r "file"
call :setAttr -r "file"
功能:
:setAttr
:: Usage:
:: call :setAttr "+r -a" "file"
setlocal
for /f "delims=" %%a in ('attrib "%~2"') do set "attrs=%%a"
set "attrs=%attrs:~0,10%"
set toggle=
if not "%attrs:H=%"=="%attrs%" set toggle=-h
if not "%attrs:S=%"=="%attrs%" set toggle=%toggle% -s
if defined toggle attrib %toggle% "%~2"
attrib %~1 "%~2"
if defined toggle attrib %toggle:-=+% "%~2"
endlocal
exit /b