我想在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"
}
答案 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
# ...
}