I am new to power shell script. I need a Power shell script to Check the available disk space and delete some old subfolders from a folder until the free space reaches threshold level.
Within "D:\InstallApp\Backup" this path I have multiple folders each with date as folder name. I have to delete some of the old dated back up folder to let the free space reach the threshold level.Thanks in Advance :)
$driveLetter = "D"
$directory = "D:\InstallApp\Backup"
$desiredGiB = 266
$desiredBytes = $desiredGiB * 1073741824
Get-PSDrive $driveLetter | ForEach-Object { $free = $_.Free }
$list = $(Get-ChildItem $directory -File | Sort-Object -Property LastWriteTime)
#Write-Output $list
if ($free -lt $desiredBytes) {
$toDelete = @()
$needed = $desiredBytes - $free
$spaceToFree = 0
foreach ($item in $list) {
$toDelete += $item
#write-Output $toDelete
$spaceToFree += $item.Length
#write-Output $spaceToFree
if ($spaceToFree -ge $needed) {
break
}
}
$toDelete | ForEach-Object {
## Remove -WhatIf when you are comfortable that this is working as intended
Remove-Item $toDelete
}
}
All the steps works fine except the deleting step. Remove-Item throws file not found exception