清除具有特定参数的目录

时间:2015-04-17 23:38:43

标签: date powershell subdirectory

我尝试创建计划任务以清除旧代码的开发目录。我已经看到了一些接近的例子,但有些事情我似乎无法做得很好。

首先,我使用的根目录中没有文件。它充满了子目录。在子目录中,我需要保留两个,无论如何都要保留所有内容。如果超过14天,其余的目录及其内容将被删除。任何目录中的任何内容都不需要按日期排序。应该考虑初始顶级目录的日期。这就是我所拥有的不正常......它删除了文件夹中的所有内容,令我感到沮丧!

# Set folder path
$dump_path = "C:\TEMP"
# Set min age of files
$max_days = "-14"
# Get the current date
$curr_date = Get-Date
# Determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)
# Delete the files older than x days on the main folder level (Folders Excluded)
Get-ChildItem $dump_path | ?{ !$_.PsIsContainer } | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item -Force -Confirm:$False
# Delete the folders (and all included content) older than x days on the main folder level (Files Excluded)
Get-ChildItem $dump_path |? {$_.psiscontainer -and $_.lastwritetime -le (get-date).adddays(-14) -and (-not($_.name -eq "SoftwareInventory;atms"))} | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item -Recurse -Force -Confirm:$False

我感谢我能得到的任何帮助,让它发挥作用。我没有写这段代码。这个和其他网站是零碎的,把我找到的部分放在一起,试图让它发挥作用。我很擅长编码。

1 个答案:

答案 0 :(得分:1)

如果您认为问题来自Where-Object

中的此条款
-not($_.name -eq "SoftwareInventory;atms")

“SoftwareInventory”和“atms”是您要保留的文件夹吗?如果是这样,语法将无法工作,因为它正在寻找与字面上称为“SoftwareInventory; atms”的文件夹的匹配。我想我们需要对该条款进行一些更新

("SoftwareInventory","atms" -notcontains $_.name)

这样使用-notcontains并匹配所有未命名为“SoftwareInventory”或“atms”的文件夹

糟糕行情?

通常这是一个复制粘贴错误,但您在我删除的问题中有奇怪的引号。

  • “可能导致问题
  • “标准报价
相关问题