Back to Basics: Change an Attribute on a File
Today's post is short and sweet... just like the PoSh Progeny!
Here's a short and sweet way to manipulate file attributes. Stuff like 'Read-only' and 'File is ready for archiving' in the below image.
First up, add an attribute. We have a file that is marked as Archive and Offline. Time to add ReadOnly.
#Attribute to add
$Attribute = "ReadOnly"
#Get the target file / folder
$TargetItem = Get-Item -Path .\Untitled1.ps1
#Get the attributes of the item
$Attributes = $TargetItem.Attributes
#Add the additional permission
$file.Attributes = $file.Attributes -bor [System.IO.FileAttributes]::$Attribute
Now let's look at file attributes.
Jolly good. Now to remove that ReadOnly. A little more considered this time, as I want to preserve Archive and Offline.
#Attribute to add
$Attribute = "ReadOnly"
#Get the target file / folder
$TargetItem = Get-Item -Path .\Untitled1.ps1
#Get the attributes of the item
$Attributes = $TargetItem.Attributes
#Split the existing attributes and remove the target one
$splitAtts = ($Attributes -split ",").trim() -replace "$Attribute"
#Loop through remaining attributes and make each a file attribute object
foreach ($SplitAtt in $SplitAtts) {
#Add file attribute objects to an array
[Array]$FileAtts += [System.IO.FileAttributes]$SplitAtt
} #end of foreach ($splitAtt in $splitAtts)
#Apply the edited attribute set
$File.Attributes = $FileAtts
Now let's look at file attributes.
Short and sweet and to the point...
Comments
- Anonymous
July 26, 2016
Good to find an expert who knows what he's talking about! - Anonymous
August 05, 2016
Thanks for sharing.