且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除文件夹中除只读文件之外的所有文件?

更新时间:2023-02-19 21:10:06

唯一可以只读的对象是文件.当您使用 Get-ChildItem cmdlet 时,您将返回 System.IO.FileInfoSystem.IO.DirectoryInfo 类型的对象.FileInfos 有一个名为 IsReadOnly 的属性.所以你可以做这一个班轮:

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

PsIsContainer 属性是由 PowerShell 创建的(Ps 前缀给出了它)并告诉该项目是文件还是文件夹.我们可以使用它只将文件传递给 Remove-Item.

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.

当您准备真正删除时删除 -WhatIf.

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