powershell脚本删除一些旧数据以释放空间达到一定限制

powershell脚本删除一些旧数据以释放空间达到一定限制,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,我不熟悉powershell脚本。我有一个powershell脚本来检查可用磁盘空间,并从文件夹中删除一些旧的子文件夹,直到可用空间达到阈值水平 我的代码会删除所有文件夹,并且不会在任何地方退出。我正在检查可用空间是否大于可用空间,并尝试终止它。($part.FreeSpace-gt$desiredBytes) 我回显了$desiredBytes、$part.FreeSpace、$directoryInfo.count。即使删除了一个很大的文件夹,这些变量的值也不会更新。因此,所有文件夹都将被删

我不熟悉powershell脚本。我有一个powershell脚本来检查可用磁盘空间,并从文件夹中删除一些旧的子文件夹,直到可用空间达到阈值水平

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

我回显了$desiredBytes、$part.FreeSpace、$directoryInfo.count。即使删除了一个很大的文件夹,这些变量的值也不会更新。因此,所有文件夹都将被删除,但仍不会终止

有人能帮我吗。提前感谢:)


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

查看我的版本:

$drive=“D:”
$directory=“$drive\Suba\Suba”
$desiredSpace=262*1gb
$subfolders=[System.Collections.ArrayList]@(获取ChildItem$directory |其中{$\ PSIsContainer}|排序LastWriteTime)
while(([wmi]“Win32_LogicalDisk.DeviceID=“$drive”).FreeSpace-lt$desiredSpace){
如果($subfolders.Count-等式0){
写入警告“没有足够的子文件夹可删除。”
打破
}
删除项$子文件夹[0]。全名-递归-强制-确认:$false
$subfolders.RemoveAt(0)
}

谢谢。但是,此版本抛出“异常调用”RemoveAt“和“1”参数:“集合大小固定”。错误,并且它首先删除邮件文件夹,甚至在搜索子文件夹名称之后,它还抛出“未找到对象”错误。@SubasriKalyankumar My bad。修复了代码。(首先将数组转换为ArrayList)非常感谢……:)它按预期工作……非常感谢……@SubasriKalyankumar请查看
where{$\u.PSIsContainer}
?仅筛选文件夹。将其删除,以获取文件夹中的所有项目,或尝试
get ChildItem$directory-Filter*.zip
仅获取zip文件。@SubasriKalyankumar您也可以使用
-File
-directory
开关,但它们在早期的Powershell版本中不存在
[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)