4.13. Making a File or Folder Read-Only

Problem

You want to prevent a file or folder from being updated by making it read-only.

Solution

Using a graphical user interface

  1. Open Windows Explorer.

  2. Browse to the file or folder you want to hide.

  3. Right-click the file or folder and select Properties.

  4. Check the box beside Read-only.

  5. Click OK.

Using a command-line interface

To make a file read-only, use the attrib.exe command:

> attrib +R <Path>

Here is an example:

> attrib +R d:\mysecretscript.vbs

To make a file available for reading and writing, use the -R option:

> attrib -R <Path>

Here is an example:

> attrib -R d:\mysecretscript.vbs

Using VBScript

' This code enables or disables the read-only attribute of a file.
' ------ SCRIPT CONFIGURATION ------
strFile = "<FilePath>"  ' e.g., d:\mysecretscript.vbs
boolReadOnly = True     ' True = read-only, False = not read-only
' ------ END CONFIGURATION ---------
set objFSO = CreateObject("Scripting.FileSystemObject")
   
' Change this to GetFolder to hide/unhide a folder
set objFile = objFSO.GetFile(strFile)
   
if boolReadOnly = True then
   if objFile.Attributes AND 1 then
      WScript.Echo "File already read-only" 
   else
      objFile.Attributes = objFile.Attributes + 1
      WScript.Echo "File is now read-only"
   end if 
else
   if objFile.Attributes AND 1 then
      objFile.Attributes = objFile.Attributes - 1
      WScript.Echo "File is not read-only"
   else
      WScript.Echo "File is already not


 read-only" 
   end if 
end if

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.