How to change files and folders attributes using PowerShell?


There are multiple files and folders attribute supported by the Windows Operating System. To check which attributes that files and folders support use DOS command attrib /?

You can see the attributes listed like Read-Only, Archive, etc. You can set the attribute using PowerShell.

For example, we have a file called TestFile.txt and its attribute is ReadOnly and we need to change it to the Archive.

PS C:\> (Get-ChildItem C:\Temp\TestFile.txt).Attributes
ReadOnly

Change Attribute code −

$file = Get-ChildItem C:\Temp\TestFile.txt
$file.Attributes = 'Archive'

So we have set the attribute to the ‘Archive’ from ‘ReadOnly’ and when you check it, the attribute should be changed.

PS C:\> (Get-ChildItem C:\Temp\TestFile.txt).Attributes
Archive

To set the multiple attributes, you can separate the values by a comma. For example,

$file = Get-ChildItem C:\Temp\TestFile.txt
$file.Attributes = 'Archive','ReadOnly'
(Get-ChildItem C:\Temp\TestFile.txt).Attributes
ReadOnly, Archive

Similar way you can change the attributes of the folder. For example,

$folder = Get-Item C:\Temp
$folder.Attributes = 'Directory','Hidden'

We will check the folder attributes now. This folder is hidden so we need to use -Hidden parameter.

PS C:\> (Get-ChildItem C:\Temp\ -Hidden).Attributes
Hidden, Directory

To change attributes on the multiple files in the same folder, you need to use foreach loop. For example,

Get-ChildItem C:\Test1\ -Recurse | foreach{$_.Attributes = 'Hidden'}

When we check their values, they should be hidden.

PS C:\> Get-ChildItem C:\Test1 -Recurse -Force

Directory: C:\Test1

Mode      LastWriteTime     Length Name
----      -------------     ------ ----
---h--    8/28/2020 7:27 AM 11 File1.txt
---h--    8/28/2020 7:49 AM 11 File2.txt

-Recurse parameter is to retrieve the data from subfolders. If you need only parent folder data attribute change then remove -Recure parameter.

Updated on: 16-Oct-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements