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

旧时模样 提交于 2019-12-04 04:20:26

问题


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

How to do it using powershell?


回答1:


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.




回答2:


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



回答3:


Check the attribute of each folder and file and then do a conditional based deletion. This is just the pseudo code.

If (-not (a readonly file)) {
delete file
}

So, to check if a given file or folder is readonly:

$item = Get-Item C:\Scripts\Test.txt
$item.IsReadOnly

HTH



来源:https://stackoverflow.com/questions/8909441/how-to-delete-all-the-files-in-a-folder-except-read-only-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!