on August 15, 2010
Attrib
command can be used to set or unset file attributes from Windows command prompt. This post explains with examples the syntax for managing the file attributes on Windows computer.
Archive attribute
To set archive attribute for the file example.doc:
attrib +a example.doc
To unset archive attribute:
attrib -a example.doc
Read-only attribute
To set read only attribute:
attrib +r example.doc
To unset read only attribute:
attrib -r example.doc
Hidden attribute
To make the file hidden :
attrib +h example.doc
To remove the hidden attribute:
attrib -h example.doc
System attribute
To set system file attribute:
attrib +s example.doc
To unset system file attribute:
attrib -s example.doc
Attrib
command works on all Windows editions(XP, Vista, Windows 7, Windows 10, Server 2K3 & 2K8)
Set file attributes in bulk
Attrib command accepts wild characters and can process files in bulk. The syntax for bulk processing is given below
attrib +[R/H/S/A] *
To set attribute for files of certain type/extension
attrib +[R/H/S/A] *.ext
To set attribute for all files in current directory
attrib +[R/H/S/A]
Example:
Set hidden attribute on all PDF files in the current directory
attrib +H *.pdf
Relevant links:
Attrib command: Not resetting hidden file
Attrib command: Not resetting system file
The `attrib` command in Windows Command Prompt is used to change the attributes of files or directories, allowing you to set them as read-only, hidden, system, or archive.
attrib +h +s example.txt
Understanding File Attributes
What Are File Attributes?
File attributes are metadata associated with files and directories that define their characteristics in a Windows file system. These attributes can dictate how the operating system interacts with these files or directories, influencing visibility, accessibility, and system behavior. Understanding file attributes is crucial for effective file management and system organization.
Types of File Attributes in Windows
-
Read-only: This attribute ensures that a file cannot be modified or deleted unless this attribute is removed. It is particularly useful for important files that should not be edited inadvertently.
-
Hidden: Files with this attribute are not visible in standard directory listings, allowing for the concealment of system files or files that should not be modified by users.
-
System: This attribute identifies files essential for the operating system’s proper function. These files are generally hidden by default to prevent accidental modification.
-
Archive: This attribute marks files to be included in backups. When a file is modified, this attribute can signal backup software to include it in routine backup processes.
Mastering Windows Cmd Arp for Networking Success
Syntax of the `attrib` Command
Basic Syntax
The `attrib` command syntax is straightforward:
attrib [attributes] [file/directory]
This structure allows you to specify the attributes you want to add or remove and the target file or directory.
Common Switches Used with `attrib`
Setting Attributes
To set file attributes, you can use the following switches:
-
+R: Use this switch to mark a file as read-only. This means it cannot be modified or deleted without first removing this attribute.
-
+H: This flag hides a file from common view. Hidden files can still be accessed if sought actively, but they won’t appear in standard file listings.
-
+S: Mark a file as a system file, indicating that it is crucial for the operating system’s operation and should be handled with care.
-
+A: This attribute is set to indicate that a file is available for archiving; that is, it can be included in backup operations.
Clearing Attributes
To clear file attributes, use the corresponding minus signs:
-
-R: This command removes the read-only attribute, allowing modifications to the file.
-
-H: Use this command to unhide a file, making it visible in normal views.
-
-S: This clears the system attribute, allowing for standard file manipulation.
-
-A: This removes the archive attribute, indicating that the file need not be included in backup processes.
Mastering Windows Cmd Alias for Effortless Command Shortcuts
Practical Examples
Checking File Attributes
To view the attributes assigned to a file, simply use the `attrib` command by typing:
attrib C:\path\to\your\file.txt
The output will display a string of letters that corresponds to the file’s attributes. For instance, «RHA» shows that the file is Read-only, Hidden, and Archive. Understanding this output is key to managing file properties effectively.
Modifying File Attributes
Setting a File as Read-only
To mark a file as read-only and prevent it from being altered, use:
attrib +R C:\path\to\your\file.txt
This command is particularly useful for protecting crucial files from accidental deletion or modification.
Hiding a File
To hide a specific file, execute the following command:
attrib +H C:\path\to\your\file.txt
This approach is beneficial for sensitive information or system files that should not be altered or deleted by users.
Setting System Attributes
You might need to mark a file important for the system as follows:
attrib +S C:\path\to\your\file.txt
When a file is designated as a system file, it is safer from user interference, reinforcing the stability of the operating system.
Clearing Attributes
To remove certain attributes from a file, for example, to unhide and allow changes, you can utilize:
attrib -H -R C:\path\to\your\file.txt
This command is crucial when you need to make a previously hidden read-only file accessible again.
Mastering Windows Cmd Route: A Concise Guide
Advanced Usage of `attrib`
Using Wildcards with `attrib`
The `attrib` command also supports wildcards, which can simplify file management when dealing with multiple files. For example, if you want to mark all `.txt` files in a directory as read-only, you can issue the command:
attrib +R C:\path\to\folder\*.txt
This command will apply the read-only attribute to every `.txt` file within the specified folder.
Combining Multiple Attributes
Sometimes, you may want to set multiple attributes simultaneously. You can do this easily by combining switches:
attrib +R +H C:\path\to\your\file.txt
This command applies both the Read-only and Hidden attributes to the specified file, providing additional security and privacy.
Unlocking The Power Of Windows Cmd Whois
Troubleshooting Common Issues
Permission Denied Errors
When executing `attrib`, you may encounter permission-denied errors. This can occur from trying to modify attributes of files located in system directories or when lacking the necessary administrative privileges. Ensure you have adequate rights before attempting any changes.
Attributes Not Changing
If you find that attributes are not updating as expected, consider checking file permissions or ensuring that the command is being executed in the correct directory. Sometimes, file locks or active processes can prevent changes from taking effect.
Windows Cmd Grep: Your Essential Guide to Text Searching
Conclusion
The `attrib` command in Windows CMD is a powerful tool for managing file and directory attributes. By understanding how to view, modify, and combine these attributes, users can enhance their file organization, protect important data, and ensure optimal system operation. Encouragement is given to practice these commands in a safe environment to master their usage.
Windows Cmd Repair: Quick Fixes You Need to Know
Additional Resources
For further exploration and deeper insights, users are encouraged to refer to official Microsoft documentation on CMD commands and additional training resources available online for mastering command line operations.
The attrib command displays or changes the file attributes for a file or folder. It’s run from the Command Prompt in all versions of Windows.
‘Attrib’ Command Availability
The attrib command is available in the Command Prompt in all Windows operating systems including Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, Windows XP, plus older versions of Windows as well.
All offline diagnostic and repair tools available with the various versions of Windows, including Advanced Startup Options, System Recovery Options, and Recovery Console, also include attrib in some capacity.
This attrib command is also available in MS-DOS as a DOS command.
The availability of certain attrib command switches and other attrib command syntax might differ from operating system to operating system.
‘Attrib’ Command Syntax & Switches
The command takes the following general form:
attrib [+a|-a] [+h|-h] [+i|-i] [+r|-r] [+s|-s] [+v|-v] [+x|-x] [drive:][path][filename] [/s [/d] [/l]]
Attrib Command Options | |
---|---|
Item | Explanation |
attrib | Execute the attrib command alone to see the attributes set on the files within the directory that you execute the command from. |
+a | Sets the archive file attribute to the file or directory. |
-a | Clears the archive attribute. |
+h | Sets the hidden file attribute to the file or directory. |
-h | Clears the hidden attribute. |
+i | Sets the ‘not content indexed’ file attribute to the file or directory. |
-i | Clears the ‘not content indexed’ file attribute. |
+r | Sets the read-only file attribute to the file or directory. |
-r | Clears the read-only attribute. |
+s | Sets the system file attribute to the file or directory. |
-s | Clears the system attribute. |
+v | Sets the integrity file attribute to the file or directory. |
-v | Clears the integrity attribute. |
+x | Sets the no scrub file attribute to the file or directory. |
-x | Clears the no scrub attribute. |
drive:, path, filename | This is the file (filename, optionally with drive and path), directory (path, optionally with drive), or drive that you want to view or change the attributes of. Wildcard use is allowed. |
/s | Use this switch to execute whatever file attribute display or changes you’re making on the subfolders within whatever drive and/or path you’ve specified, or those within the folder you’re executing from if you don’t specify a drive or path. |
/d | This attrib option includes directories, not only files, to whatever you’re executing. You can only use /d with /s. |
/l | The /l option applies whatever you’re doing with the attrib command to the Symbolic Link itself instead of the target of the Symbolic Link. The /l switch only works when you’re also using the /s switch. |
/? | Use the help switch with the attrib command to show details about the above options right in the Command Prompt window. Executing attrib /? is the same as using the help command to execute help attrib. |
In Recovery Console, +c and -c switches apply to attrib. They set and clear the compressed file attribute, respectively. Outside of this diagnostic area in Windows XP, use the compact command to handle file compression from the command line.
When a wildcard is allowed with attrib, it means that you can use an asterisk to apply the attribute to a group of files. However, if applicable, you have to clear the system or hidden attribute first before you can change any of the file’s other attributes.
Attrib Command Examples
Here are some examples of how this command can be used:
Apply Read-Only Attribute
attrib +r c:\windows\system\secretfolder
In the above example, attrib turns on the read-only attribute, using the +r option, for the secretfolder directory located in c:\windows\system.
Clear Hidden Attribute
attrib -h c:\config.sys
In this example, the config.sys file located in the root directory of the c: drive has its hidden file attribute cleared by use of the -h option.
Clear Multiple Attributes
attrib -h -r -s c:\boot\bcd
This time, attrib removes several file attributes from the bcd file, an important file that must be working for Windows to start. In fact, executing the attrib command, as shown above, is a key part of the process outlined in the steps necessary for rebuilding the BCD in Windows.
Apply and Clear Attributes
attrib +a f:*.* & attrib -a f:*.bak
With the above example, we’re applying +a to set the archive attribute on all files that exist on the f: drive, but then using & to remove the archive attribute on every file on f: that has the .bak file extension.
In the above example, BAK files indicate files that have already been backed up, meaning that they don’t need to be archived/backed up again, hence the need to remove the archive attribute.
Display a File’s Attributes
attrib myimage.jpg
To end with a simple attrib example, this one simply displays the attributes of a file named myimage.jpg. If you were to remove the second half and execute only the attrib command, it would display the attributes for all files in the current directory.
Attrib Command Errors
As with most commands in Command Prompt, use double-quotes around a folder or file name that has spaces. If you forget to do this with the attrib command, you’ll get a «Parameter format not correct -« error.
For example, instead of typing my folder in Command Prompt to show the path to a folder by that name, you’d type «my folder» to use the quotes.
Attrib command errors like Access Denied mean that you don’t have enough access to the file(s) you’re trying to make attribute changes to. Take ownership of those files in Windows and then try again.
The +i, -i, and /l attrib command options were first available in Windows Vista and have been retained up through Windows 10.
The +v, -v, +x, and -x switches for the attrib command are only available in Windows 7, Windows 8, and Windows 10.
‘Attrib’-Related Commands
It’s common for the xcopy command to effect a file’s attribute after it backs up something. For example, the xcopy command’s /m switch turns off the archive attribute after the file has been copied.
Similarly, the xcopy /k switch keeps a file’s read-only attribute once it’s been copied.
Viewing Attributes in Explorer
You can also view and manage attributes for files and folders in File Explorer using regular menu buttons. This might be preferred for you if you’re not familiar with the command line.
Do this by right-clicking the object and going into its Properties > General tab.
Thanks for letting us know!
Get the Latest Tech News Delivered Every Day
Subscribe
Quick Links
-
What Attributes Can You Use?
Windows offers a wide variety of tools that you can access using your command prompt window including the “attrib” tool which is designed to help you search for files by location and name then view and modify their file attributes.
What Attributes Can You Use?
Now that you have your elevated command prompt window open, you will need to know what types of attributes you can edit using the “attrib” tool. There are two main types of attributes, “basic” and “extended.”
Basic Attribute Switches (R, H, A, S)
- R – This command will assign the “Read-Only” attribute to your selected files or folders.
- H – This command will assign the “Hidden” attribute to your selected files or folders.
- A – This command will prepare your selected files or folders for “Archiving.”
- S – This command will change your selected files or folders by assigning the “System” attribute.
“Attrib” Syntax
You will need to know the proper syntax to use for the “attrib” tool before you get started.
ATTRIB [+ attribute | - attribute] [pathname] [/S [/D]]
In this syntax, you will need to know what the different switches and parameters represent.
- The + and – indicate whether you will activate or deactivate the attribute specified.
- The attributes you can use are those explained above.
- The “/S” signifies that you want to search the entire path specified including subfolders for a particular file.
- The “/D” signifies that you want to include any process folders as well.
- The pathname indicates the location of your target folder or file. The proper syntax for path files is shown below.
Drive and/or filename - C:\*.* OR C:\Users\Owner\Desktop\samplefile.txt
If you decide not to specify any of the attributes listed above, the files or folders will revert to their current attribute settings.
Let’s Practice
Now that you know the types of attributes you can use and the syntax you need to use, let’s practice some scenarios. Open the start menu in Windows 7 and 10 or open the search function in Windows 8 and search for CMD. Next, right-click on it and then press “Run as administrator.” While you don’t need to open an elevated command prompt window, it will help you to avoid any confirmation dialog boxes.
Scenario 1 — Clear “Hidden and System” attributes with a single command to make your files or folders normal.
For this example, we will first create a file in your “Documents” directory called “sample.txt.” First, open up the directory and right-click somewhere in the window, move your mouse to the “New” section, click on “Text File,” and name the document “sample.”
Now go to your CMD window. We will change the file’s properties so that it is both a system file, and hidden. Do this by entering the following command.
attrib +h +s C:\Users\Martin\Documents\sample.txt
Remember to substitute the “Martin” section of the path parameter with your computer’s username.
Once you have done this, you will notice that the file has disappeared from your documents folder. Now that we want to remove the System and Hidden file attributes from “sample.txt,” we will need to use the following simple command.
attrib –h –s C:\Users\Martin\Documents\sample.txt
Note that if you try to enter the file name without a path, you will receive an error. You must remember to add the entire path to your command. Now, if you go back to your “Documents” directory, you will see the file in the list.
Scenario 2 — Make all text files in your “Downloads” folder read-only system files.
Now we will create a few sample text files in the “Downloads” directory and we will edit them using the “attrib” tool so that they all become read-only system files.
Once you have your sample text files created, it is time to use CMD to write a command that will change the attributes of all text files in a specified directory to “Read-Only and System.” For this, we will need to use wildcards to select all the text files. You can do this by using the command below. Remember to substitute the “Martin” section with your computer’s username.
attrib +r +s C:\Users\Martin\Downloads\*.txt
Now you can open your downloads folder, right-click on one of the text files and then select properties. You will note that the file attributes have been changed. To remove these settings simply use the same command, but replace the plus signs with minus signs.
attrib -r -s C:\Users\Martin\Downloads\*.txt
Scenario 3 – Prepare a file located on your desktop for archiving.
Let’s start by creating a sample text file on the desktop. Now, navigate to your CMD window and enter the following string to prepare the selected file for archiving.
attrib +a C:\Users\Martin\Desktop\sample.txt
Scenario 4 — Hide an entire Directory/Folder on your desktop.
Let’s say for example, you have sensitive data in a folder on your desktop called “Private,” and you want to hide it along with all its files and subfolders. It is important to note that when you are working with directory attributes, you cannot use wildcards such as “? and *.” You will need to be explicit in your file path. First, you need to create a folder on your desktop and put a few files in it. Once you have done that, navigate to your CMD window and enter the following command.
attrib +h C:\Users\Martin\Desktop\Private
Once you press “Enter,” the entire folder will disappear since it will be hidden.
Now you can play with some of the other settings to make changes to any file attributes on your computer.
Команда attrib предназначена для просмотра или изменения атрибутов файлов и папок через командную строку Windows. Данная программа доступна в Windows 10, Windows 7, Windows XP и в более старых версиях Windows. В данной статье мы рассмотрим синтаксис, параметры и примеры использования этой команды.
Содержание
Синтаксис команды attrib
Синтаксис команды attrib выглядит следующим образом:
attrib [{+|-}r] [{+|-}a] [{+|-}s] [{+|-}h] [{+|-}i] [<drive>:][<path>][<filename>] [/s [/d] [/l]]
Где
+a
-a |
Добавляет/удаляет атрибут «Архивный» для файла или каталога. |
+h
-h |
Добавляет/удаляет атрибут «Скрытый» для файла или каталога. |
+i
-i |
Добавляет/удаляет атрибут «Не проиндексировано» для файла или каталога. |
+r
-r |
Добавляет/удаляет атрибут «Только для чтения» для файла или каталога. |
+s
-s |
Добавляет/удаляет атрибут «Системный» для файла или каталога. |
+i
-i |
Добавляет/удаляет атрибут «Не проиндексировано» для файла или каталога. |
[<drive>:] [<path>] [<filename>] | Путь к папке или файлу. |
/s | Включает обработку файлов и папок в текущем каталоге и в подкаталогах. |
/d | Включает обработку файлов и папок. |
/l | Включает обработку самой символической ссылки, а не ее цели. |
/? | Просмотр справки |
Как пользоваться командой attrib
Для того чтобы просмотреть атрибуты для всех файлов в текущей папке достаточно просто выполнить команду «attrib» без каких-либо параметров.
attrib
Для того чтобы получить информацию не только о файлах, но и папках, добавляем параметр «/d».
attrib /d
Для просмотра атрибутов конкретного файла или папки нужно указать их название или полный путь. Если файл или папка содержит пробелы, то название нужно брать в двойные кавычки.
attrib /d folder attrib file.txt
Чтобы добавить какой-либо атрибут нужно указать соответствующий параметр со знаком «плюс». Например, для того чтобы добавить «Только для чтение» нужно использовать «+r». Удаление атрибута выполняется аналогичным способом, только со знаком минус.
attrib +r c:\temp2\file.txt attrib -r c:\temp2\file.txt
При добавлении или удалении атрибутов для папок всегда нужно использовать параметр «/d».
attrib +h c:\temp2\folder /d attrib -h c:\temp2\folder /d
Примеры использования attrib
При необходимости, с помощью команды «attrib» можно добавлять и удалять сразу несколько атрибутов за раз. Ниже приведено несколько примеров такого использования данной команды.
Добавляем атрибуты «Системный», «Скрытый», «Только для чтения» и для файла «c:\file.txt».
attrib +s +h +r c:\file.txt
Удаляем атрибуты «Системный», «Скрытый», «Только для чтения» для файла «c:\file.txt».
attrib -s -h -r c:\file.txt
Добавляем атрибуты «Системный», «Скрытый», «Только для чтения» для всех файлов в папке «c:\temp2»
attrib +s +h +r c:\temp2\*
Удаляем атрибуты «Системный», «Скрытый», «Только для чтения» для всех файлов в папке «c:\temp2»
attrib -s -h -r c:\temp2\*
Добавляем атрибуты «Системный», «Скрытый», «Только для чтения» для всех файлов и папок в папке «c:\temp2»
attrib +s +h +r c:\temp2\* /d
Удаляем атрибуты «Системный», «Скрытый», «Только для чтения» для всех файлов и папок в папке «c:\temp2»
attrib -s -h -r c:\temp2\* /d
Добавляем атрибуты «Системный», «Скрытый» для всех файлов и папок в папке «c:\temp2», а также для всех вложенных папок и файлов.
attrib +s +h c:\temp2\* /d /s
Удаляем атрибуты «Системный», «Скрытый» для всех файлов и папок в папке «c:\temp2», а также для всех вложенных папок и файлов.
attrib -s -h c:\temp2\* /d /s
Ошибки при использовании команды attrib
Если при попытке изменить атрибуты вы получаете ошибку «Ошибка в формате параметра», то скорее всего проблема в том, что файл или папка содержит пробелы. Для решения этой проблемы нужно просто взять путь к файлу или папке в двойные кавычки.
Еще одна возможная проблема – ошибка «Доступ запрещен». В этом случае для изменения атрибутов нужно запустить командную строку с правами администратора либо изменить права доступа к данному файлу.
Автор
Александр Степушин
Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.
Остались вопросы?
Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.