【问题标题】:How to delete all the files in a folder except read-only files?如何删除文件夹中除只读文件外的所有文件?
【发布时间】:2012-01-19 02:45:45
【问题描述】:

我想从一个文件夹中删除所有文件和子文件夹,只读文件除外。

如何使用 powershell 做到这一点?

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    作为参考,这在 V3 中更容易一些:

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

    或短(别名)版本:

    dir -at !r | ri -r -f -wh
    

    【讨论】:

      【解决方案2】:

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

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

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

      当您准备好删除时删除-WhatIf

      【讨论】:

        【解决方案3】:

        检查每个文件夹和文件的属性,然后进行基于条件的删除。这只是伪代码。

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

        因此,检查给定文件或文件夹是否为只读:

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

        HTH

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-12-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多