gpt4 book ai didi

powershell - 用于删除最早的文件夹直到达到特定阈值的脚本

转载 作者:行者123 更新时间:2023-12-03 00:15:46 26 4
gpt4 key购买 nike

我想在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"
}

最佳答案

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

关于powershell - 用于删除最早的文件夹直到达到特定阈值的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com