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
Remove-Item
expects strings for the -Path
(check out Remove-Item -?
), so the file items are converted to strings, which will be the file names only, not full paths.
Use
$toDelete | foreach { Remove-Item $_.FullName }
or better
$toDelete | Remove-Item