Anton Krouglov
Anton Krouglov

Reputation: 3399

How to change extended windows file attributes via Powershell without using attrib.exe?

This seems to be a quite simple question, yet googling gave me nothing. Here is the error (PS 5.1, win 10.0.14393 x64):

Set-ItemProperty $myFileInfo -Name Attributes -Value ([System.IO.FileAttributes]::Temporary)
The attribute cannot be set because attributes are not supported. Only the following attributes can be set: Archive, Hidden, Normal, ReadOnly, or System.

attrib.exe seems to support most of System.IO.FileAttributes. Unfortunately is does not seem to work with files referenced using FileSystem PSDrives. That is what I am using extensively.

Making wrapper for SetFileAttributes kernel API call would be the last resort.

Am I missing any other [more simple] ways setting these extended file attributes?

PS. Apart from [System.IO.FileAttributes]::Temporary I am interested in setting [System.IO.FileAttributes]::NotContentIndexed.

Upvotes: 3

Views: 3226

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36332

You can edit the Attributes property of a [FileInfo] object directly. For example, if you wanted to exclude all files in the C:\Temp folder from being content indexed, you could do this:

Get-ChildItem C:\Temp | ForEach{
    $_.Attributes = $_.Attributes + [System.IO.FileAttributes]::NotContentIndexed
}

That would get each file, and then add the [System.IO.FileAttributes]::NotContentIndexed attribute to the existing attributes. You could probably filter the files to make sure that the attribute doesn't already exist before trying to add it, since that may throw errors (I don't know, I didn't try).

Edit: As noted by @grunge this does not work in Windows Server 2012 R2. Instead what you have to do is reference the value__ property, which is the bitwise flag value, and add the bitwise flag for NotContentIndexed. This should work for you on any Windows OS:

Get-ChildItem C:\Temp | ForEach{
    $_.Attributes = [System.IO.FileAttributes]($_.Attributes.value__ + 8192)
}

Upvotes: 6

Related Questions