Question:
I have tried many code but still I am not able to remove read-only property of that particular folder.
Below is the code which removes read-only property of the files present under that folder but does not remove read-only attribute of that Folder :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$Path = "C:\Suraj\powershell scripts\review script" $Files = Get-ChildItem $Path -Recurse ForEach ($File in $Files) { Write-Host file:$File IsReadOnly: $File.IsReadOnly if ($File.Attributes -ne "Directory" -and $File.Attributes -ne "Directory, Archive") { try { Set-ItemProperty -Path $Path"\"$File -name IsReadOnly -value $false } catch { Write-Host "Error at file " $Path "\" $File } } } |
Answer:
Whether a folder has the ReadOnly
attribute set or not, can be verified with:
1 2 3 |
$folder = Get-Item -Path path/to/folder $folder.Attributes |
Default output will be:
Directory
To add the ReadOnly
attribute, just execute:
1 2 |
$folder.Attributes = $folder.Attributes -bor [System.IO.FileAttributes]::ReadOnly |
If you display the attributes again, it should look like this:
ReadOnly, Directory
To remove the ReadOnly
attribute, just execute:
1 2 |
$folder.Attributes = $folder.Attributes -band -bnot [System.IO.FileAttributes]::ReadOnly |
The attributes look like that again:
Directory
As you can see, it is indeed possible to add and remove the ReadOnly
attribute, but as others already mentioned in the comments, it won’t have much of an effect.
The ReadOnly
attribute can also be added and/or removed in a more readable way:
1 2 3 |
$folder.Attributes += 'ReadOnly' $folder.Attributes -= 'ReadOnly' |
But be aware, that this does not work reliably, if you add the attribute when it already exists or if you remove it when it does not exist. This is because the attributes are stored in a bit field. Subtracting an unset bit will flip many other bits instead of just this one bit.