删除最旧文件夹直到达到特定阈值的脚本

Script for deleting the oldest folder until a certain threshold

我想在 PowerShell 中制作一个脚本来计算目录的使用 space,如果它大于阈值,我想根据创建日期删除最旧的文件夹,直到低于阈值.

我设法做到了这样的事情,但我不明白为什么我的 while 条件不符合我的要求。

$directory = "D:\TEST"   # root folder
$desiredGiB = 25    # Limit of the directory size in GB

#Calculate used space of the directory
$colItems = (Get-ChildItem $directory -recurse |
            Measure-Object -property length -sum)
"{0:N2}" -f ($colItems.sum / 1GB) + " GB"
# store the size of the folder in the variable $size
$size = "{0:N2}" -f ($colItems.sum/1GB)
Write-Host "$size"
Write-Host "$desiredGiB"

#loop for deleting the oldest directory based on creation time
while ($size -gt $desiredGiB) {
    # get the list of directories present in $directory sorted by creation time
    $list = @(Get-ChildItem $directory |
            ? { $_.PSIsContainer } |
            Sort-Object -Property CreationTime)
    $first_el = $list[0]    # store the oldest directory
    Write-Host "$list"
    Write-Host "$first_el"
    Remove-Item -Recurse -Force $directory$first_el

    #Calculate used space of the Drive\Directory
    $colItems = (Get-ChildItem $directory -recurse |
                Measure-Object -property length -sum)
    # store the size of the folder in the variable $size
    $size = "{0:N2}" -f ($colItems.sum/1GB)
    Write-Host "$size"
}
$desiredGiB = 25

while ($size -gt $desiredGiB) {
    # ...
    $size = "{0:N2}" -f ($colItems.sum/1GB)
    # ...
}

你在这里比较一个整数和一个字符串。

您可以改为这样做,以在 $size:

中保留一个整数值
$desiredGiB = 25

while ($size -gt $desiredGiB) {
    # ...
    $size = $colItems.Sum / 1GB
    $displayedSize = "{0:N2}" -f $size
    # ...
}