[英]Windows batch file: How to make a hidden or system file read-only (or not read-only) while retaining its hidden and system attributes?
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>
(我假设system属性的工作方式与上述相同,但我尚未进行测试。)
因此, attrib
可以用于此目的-但前提是该批处理文件知道该文件是否已隐藏或系统,然后可以在+r
后面加上适当的+h
或+s
。
最好的方法是什么?
将隐藏属性和系统属性保存在变量中,清除并在需要时重新应用。
用法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.