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

后端 未结 3 766
春和景丽
春和景丽 2021-01-20 21:14

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

How to do it using powershell?

3条回答
  •  执笔经年
    2021-01-20 21:49

    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.

提交回复
热议问题