清除具有特定参数的目录

Clearing a directory with specific parameters

我正在尝试创建一个计划任务来清除旧代码的开发目录。我见过一些接近的例子,但有几件事我似乎不太正确。

首先,我正在使用的根目录中没有文件。它充满了子目录。在子目录中,我需要保留两个,无论如何都包含它们的所有内容。如果超过 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

感谢我能得到的任何帮助,让它发挥作用。我没有写这段代码。它是来自这个和其他站点的零碎的,将我发现的碎片放在一起,试图让它工作。我在编码方面很新。

如果您觉得您的问题来自 Where-Object

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

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

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

因此使用 -notcontains 并将匹配所有未命名为 "SoftwareInventory" 或 "atms"

的文件夹

引用错误?

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

  • “可能会导致问题
  • " 标准报价