我正在尝试删除给定文件夹的子文件夹中的所有文件而不删除子文件夹本身。我尝试了各种各样的例子,但他们并没有按照我的预期行事。
我正在尝试协商的文件树的基本结构是:
C:\Backups\Subfolder1 C:\Backups\Subfolder2 C:\Backups\Subfolder3
我正在使用以下代码:
$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
子句,则包含子文件夹中的文件,但所有目录也都包含在内。
有人可以告诉我如何将文件包含在子文件夹中,同时仍然忽略子文件夹本身吗?
答案 0 :(得分:1)
如果您使用的是PowerShell 3.0,只需使用-File
开关:
$limit = (Get-Date).AddDays(-14)
$path = "C:\Backups"
Get-ChildItem -Path $path -File -Recurse | where { $_.LastWriteTime -lt $limit } | Remove-Item
答案 1 :(得分:0)
$limit = (Get-Date).AddDays(-14)
$files = Get-ChildItem -Path C:\Backups -Directory:$false -Recurse
$files | ForEach-Object -Process {
if($_.CreationTime -lt $limit)
{
Remove-Item $_.FullName -Force
}
}
-Directory:$False
参数意味着您不必担心删除任何目录,因为它们不会包含在数组中。
答案 2 :(得分:0)
以下代码适合我。你是旧版本的PowerShell吗?
$limit = (Get-Date).AddDays(-14)
$path = "C:\Users\nathan.cooper\Documents"
Get-ChildItem -Path $path -Recurse -Force |
where { (! $_.PSIsContainer) -and ($_.LastWriteTime -lt $limit) } |
Remove-Item -whatif