【问题标题】:Power shell script to delete some old data to free up space upto certain limitPower shell脚本删除一些旧数据以释放空间达到一定限制
【发布时间】:2020-10-29 00:53:46
【问题描述】:

我是 power shell 脚本的新手。我有一个 Power shell 脚本来检查可用磁盘空间并从文件夹中删除一些旧的子文件夹,直到可用空间达到阈值水平。

我的代码删除了所有文件夹,并且不会在任何地方退出。我正在检查可用空间是否大于可用空间并尝试终止它。 ($part.FreeSpace -gt $desiredBytes)..

我已经回应了 $desiredBytes、$part.FreeSpace、$directoryInfo.count。即使删除了一个巨大的文件夹,这些变量的值也不会更新。所以,所有文件夹都被删除了,但它仍然没有终止。

有人可以帮我解决这个问题吗?提前致谢:)

[WMI]$part = "Win32_LogicalDisk.DeviceID='D:'"
$directory = "D:\Suba\Suba\"
$desiredGiB = 262

$desiredBytes = $desiredGiB * 1073741824

$directoryInfo = Get-ChildItem $directory | Measure-Object
$directoryInfo.count #Returns the count of all of the objects in the directory

do{
if($part.FreeSpace -gt $desiredBytes)
{ exit
}
if ($directoryInfo.count -gt 0) {
echo $desiredBytes
echo $part.FreeSpace
echo $directoryInfo.count
    foreach ($root in $directory) {
      Get-ChildItem $root -Recurse |
            Sort-Object CreationTime |
             Select-Object -First 1 |
            Remove-Item -Force 
   }
 }
else
{ 
    Write-Host "Enough Files are not there in this directory!!"
    exit
}
}
while($part.FreeSpace -lt $desiredBytes)

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0


    【解决方案1】:

    问题是,每次删除子文件夹后,您都需要再次进行 WMI 查询,因此可用空间被更新。

    查看我的版本:

    $drive = "D:"
    $directory = "$drive\Suba\Suba"
    $desiredSpace = 262 * 1gb
    
    $subfolders = [System.Collections.ArrayList]@(Get-ChildItem $directory | where { $_.PSIsContainer } | sort LastWriteTime)
    while (([wmi]"Win32_LogicalDisk.DeviceID='$drive'").FreeSpace -lt $desiredSpace) {
        if ($subfolders.Count -eq 0) {
            Write-Warning "Not enough sub-folders to delete."
            break
        }
        Remove-Item $subfolders[0].FullName -Recurse -Force -Confirm:$false
        $subfolders.RemoveAt(0)
    }
    

    【讨论】:

    • 谢谢。但是,这个版本抛出“异常调用“RemoveAt”和“1”参数:“集合是固定大小的。”错误并且它首先删除邮件文件夹,甚至在此之后它搜索子文件夹的名称和它会抛出找不到对象的错误。
    • @SubasriKalyankumar 我的错。修复了代码。 (先将数组转为ArrayList)
    • 非常感谢.. :) :) 它按预期工作.. 非常感谢..
    • @SubasriKalyankumar 看到where { $_.PSIsContainer }?仅过滤文件夹。删除它,以获取文件夹中的所有项,或尝试Get-ChildItem $directory -Filter *.zip 仅获取 zip 文件。
    • @SubasriKalyankumar 您也可以使用-File-Directory 开关,但它们在早期的Powershell 版本中不存在
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    相关资源
    最近更新 更多