I would like to delete all the files and subfolders from a folder except read-only files.
How to do it using powershell?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The only objects that can be read-only are files. When you use the
Get-ChildItemcmdlet you are getting objects of typeSystem.IO.FileInfoandSystem.IO.DirectoryInfoback. The FileInfos have a property namedIsReadOnly. So you can do this one liner:dir -recurse -path C:\Somewhere | ? {-not $_.IsReadOnly -and -not $_.PsIsContainer} | Remove-Item -Force -WhatIfThe
PsIsContainerproperty 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 toRemove-Item.Remove
-WhatIfwhen you are ready to delete for real.