Windows批处理文件:如何使隐藏文件或系统文件只读(或非只读),同时保留其隐藏属性和系统属性



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:somewherefoo.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一起包含。

最好的方法是什么?

将隐藏属性和系统属性保存在变量中,必要时清除并重新应用。

用法:

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

相关内容

  • 没有找到相关文章

最新更新