Skip to main content

Manage and Change the Attributes of a File

Problem

You want to update the ReadOnly, Hidden, or System attributes of a file.

Solution

Most of the time, you will want to use the familiar attrib.exe program to change the attributes of a file:

attrib +r test.txt

attrib s test.txt To set only the ReadOnly attribute, you can optionally set the IsReadOnly property on the file:

$file = GetItem test.txt $file.IsReadOnly = $true

To apply a specific set of attributes, use the Attributes property on the file:

$file = GetItem test.txt $file.Attributes = "ReadOnlyNotContentIndexed"

Directory listings show the attributes on a file, but you can also access the Mode or Attributes property directly:

PS >$file.Attributes = "ReadOnly","System","NotContentIndexed" PS >$file.Mode rs PS >$file.Attributes ReadOnly, System, NotContentIndexed

Discussion

When the GetItem or GetChildItem cmdlets retrieve a file, the resulting file has an Attributes property. This property doesn’t offer much in addition to the regular attrib.exe program, although it does make it easier to set the attributes to a specific state.

Be aware that setting the Hidden attribute on a file removes it from most default views. If you want to retrieve it after hiding it, most commands require a –Force parameter. Similarly, setting the ReadOnly

attribute on a file causes most write operations on that file to fail unless you call that command with the –Force parameter.

If you want to add an attribute to a file using the Attributes property (rather than attrib.exe for some reason), this is how you would do that:

$file = GetItem test.txt $readOnly = [IO.FileAttributes] "ReadOnly" $file.Attributes = $file.Attributes bor $readOnly

Help Category