用于删除最旧文件夹的脚本,直到达到某个阈值

时间:2015-12-10 09:12:12

标签: powershell powershell-v2.0

我想在PowerShell中创建一个脚本来计算目录的已用空间,如果它大于阈值我想根据创建日期删除最旧的文件夹,直到我达到阈值。

我设法做了这样的事情,但我不明白为什么我的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"
}

1 个答案:

答案 0 :(得分:0)

$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
    # ...
}