Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 用于删除最旧文件夹直到达到某个阈值的脚本_Powershell_Powershell 2.0 - Fatal编程技术网

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

Powershell 用于删除最旧文件夹直到达到某个阈值的脚本,powershell,powershell-2.0,Powershell,Powershell 2.0,我想在PowerShell中生成一个脚本,用于计算目录的已用空间,如果该脚本大于阈值,我想根据创建日期删除最旧的文件夹,直到低于阈值为止 我设法做了这样的事情,但我不明白为什么我的,而条件不是我想要的 $directory = "D:\TEST" # root folder $desiredGiB = 25 # Limit of the directory size in GB #Calculate used space of the directory $colItems = (G

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

我设法做了这样的事情,但我不明白为什么我的
,而
条件不是我想要的

$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"
}
这里比较的是一个整数和一个字符串

您可以这样做,以在$size中保留整数值:

$desiredGiB = 25

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

$size=“{0:N2}”-f($colItems.sum/1GB)
确实创建了一个字符串!您希望将$size保留为int以进行比较,并只输出该字符串。谢谢您的回答。我已经做了修改,现在似乎正在工作。
$desiredGiB = 25

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