Powershell - 删除旧文件夹但不删除旧文件
Powershell - delete old folders but not old files
我有以下代码可以保留在我不想再保留的旧文件夹之上
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } |
Remove-Item -Force -EA SilentlyContinue
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path
$_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer })
-eq $null } | Remove-Item -Force -Recurse -EA SilentlyContinue
它会删除超过特定天数 ($limit) 的所有内容,包括文件和文件夹。
但是,我所追求的只是删除旧文件夹及其内容。
例如,一天旧的文件夹中可能有一年前的文件,但我想保留该文件夹和旧文件。上面的代码保留文件夹但删除文件。我想要做的就是删除根目录中早于 $limit 的文件夹(及其内容),否则保留其他文件夹和内容。
提前致谢。
好吧,看看这个:
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { !$_.PSIsContainer -and $_.CreationTime -ge $limit } |
Remove-Item -Force -EA SilentlyContinue
基本上就是说"everything not a folder and older than specified is removed"。所以你的第一步是删除它。
第二部分只是删除空文件夹,您可以保持原样,也可以添加到 Where 语句以包含 CreationTime:
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit -and (Get-ChildItem -Path
$_.FullName -Recurse -Force | Where-Object { $_.CreationTime -lt $limit })
-eq $null } | Remove-Item -Force -Recurse -EA SilentlyContinue
第二个 Where 语句 returns 比 $limit 新的文件和文件夹的列表,只有当它为空时才删除文件夹。
我有以下代码可以保留在我不想再保留的旧文件夹之上
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } |
Remove-Item -Force -EA SilentlyContinue
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path
$_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer })
-eq $null } | Remove-Item -Force -Recurse -EA SilentlyContinue
它会删除超过特定天数 ($limit) 的所有内容,包括文件和文件夹。 但是,我所追求的只是删除旧文件夹及其内容。
例如,一天旧的文件夹中可能有一年前的文件,但我想保留该文件夹和旧文件。上面的代码保留文件夹但删除文件。我想要做的就是删除根目录中早于 $limit 的文件夹(及其内容),否则保留其他文件夹和内容。
提前致谢。
好吧,看看这个:
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { !$_.PSIsContainer -and $_.CreationTime -ge $limit } |
Remove-Item -Force -EA SilentlyContinue
基本上就是说"everything not a folder and older than specified is removed"。所以你的第一步是删除它。
第二部分只是删除空文件夹,您可以保持原样,也可以添加到 Where 语句以包含 CreationTime:
Get-ChildItem -Path $path -Recurse -Force -EA SilentlyContinue|
Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit -and (Get-ChildItem -Path
$_.FullName -Recurse -Force | Where-Object { $_.CreationTime -lt $limit })
-eq $null } | Remove-Item -Force -Recurse -EA SilentlyContinue
第二个 Where 语句 returns 比 $limit 新的文件和文件夹的列表,只有当它为空时才删除文件夹。