Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all the files in a folder except read-only files?

I would like to delete all the files and subfolders from a folder except read-only files.

How to do it using powershell?

like image 486
Samselvaprabu Avatar asked Feb 04 '26 04:02

Samselvaprabu


2 Answers

For reference, this is a bit easier in V3:

Get-ChildItem -Attributes !r | Remove-Item -Recurse -Force -WhatIf

or the short (alias) version:

dir -at !r | ri -r -f -wh
like image 173
Keith Hill Avatar answered Feb 06 '26 01:02

Keith Hill


The only objects that can be read-only are files. When you use the Get-ChildItem cmdlet you are getting objects of type System.IO.FileInfo and System.IO.DirectoryInfo back. The FileInfos have a property named IsReadOnly. So you can do this one liner:

dir -recurse -path C:\Somewhere | ? {-not $_.IsReadOnly -and -not $_.PsIsContainer} | Remove-Item -Force -WhatIf

The PsIsContainer property is created by PowerShell (Ps prefix gives it away) and tells whether or not the item is a file or folder. We can use this to pass only files to Remove-Item.

Remove -WhatIf when you are ready to delete for real.

like image 35
Andy Arismendi Avatar answered Feb 06 '26 02:02

Andy Arismendi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!