powershell - 删除子文件夹中超过 x 天的文件

标签 powershell

我试图删除给定文件夹的子文件夹中的所有文件,而不删除子文件夹本身。我尝试了各种示例,但它们没有达到我的预期。

我尝试协商的文件树的基本结构是:

C:\Backups\Subfolder1
C:\Backups\Subfolder2
C:\Backups\Subfolder3

and I am using the following code:

$limit = (Get-Date).AddDays(-14)
$path  = "C:\Backups"

Get-ChildItem -Path $path -Recurse -Force |
    Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } |
    Remove-Item -WhatIf

我发现尽管使用了 -Recurse 标志,但子目录中的文件仍被忽略,尽管 C:\Backups 目录中的所有文件都包含在内。如果我删除 !$_.PSIsContainer 子句,则包含子文件夹中的文件,但所有目录也包含在内。

谁能告诉我如何将文件包含在子文件夹中,同时仍然忽略子文件夹本身?

最佳答案

如果您使用的是 powershell 3.0,则只需使用 -File 开关即可:

$limit = (Get-Date).AddDays(-14)
$path = "C:\Backups"
Get-ChildItem -Path $path -File -Recurse | where { $_.LastWriteTime -lt $limit } | Remove-Item

关于powershell - 删除子文件夹中超过 x 天的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39575887/

相关文章:

windows - Powershell:始终生成空文件(比较对象的输出)

powershell - 如何在 psake 中调用 exec 到具有可变路径的可执行文件?

powershell - 导出-PfxCertificate : Cannot export non-exportable private key

regex - 文本操作问题 - 如何在已知值之后替换文本

c# - 将 Powershell 窗口的输出提取到字符串

powershell - 用户设置不适用于格式化 PowerShell 代码

powershell - 通过 powershell 安装 docker 时出错

powershell - 收集文件权限,导出为 CSV,导出 "Access Denied"文件路径

arrays - 如何将 AD 计算机名称传递给数组?

powershell - 如何使用 Ansible 中的自定义事实从 Windows 主机检索已安装软件的列表