Need help with scripts

cburbs

Distinguished
Jan 3, 2010
38
0
18,530
I am looking for some help with either a batch file or vbscript to do the following:

1) I have folders on my homenetwork that I don't want to go over say 20gb size. So once they hit say 24gb I want a script to run nightly/weekly that would watch that folder and once it is over it would delete the oldest file in that folder and loop until the folder is no longer over 20gb.

2) Almost same concept but would want to delete the oldest files in a series where more than N shows in the series already exist. So say I have a folder called "TV Shows". In this folder I don't want it to be more than 20 shows in that folder. Once it goes over it would delete the oldest show in that folder until there are only 20 shows.

thanks

 
This is easy to do using PowerShell, Microsoft's new scripting environment that's built into every version of Windows 7. Here are two scripts which do what you asked. You put each one into a file with a ".ps1" file type and then open up a PowerShell console (Start -> All Programs -> Accessories -> Windows PowerShell -> Windows PowerShell) to run them. You need to type "set executionpolicy unrestricted" once to allow scripts to run on the system, then you just type the full path to the script file to run it. If the script is in the current default folder, then type ".\" as the path name.


# Delete oldest file in directory "D:\X" until no more than 20GB remain:

$Files = get-childitem D:\X | where-object { $_ -is [IO.FileInfo] } | sort lastwritetime
$TotalSize = ($Files | measure-object length -sum).sum
if ($TotalSize -gt 20GB)
{
foreach ($File in $Files)
{
$TotalSize -= $File.Length
$File.Delete()
if ($TotalSize -le 20GB) { break }
}
}


# Delete oldest file in directory "D:\X" until no more than 2 files remain:

$Files = get-childitem D:\X | where-object { $_ -is [IO.FileInfo] } | sort lastwritetime
$FileCount = $Files.Count
if ($FileCount -gt 20)
{
foreach ($File in $Files)
{
$FileCount--
$File.Delete()
if ($FileCount -le 20) { break }
}
}
 
If I have folder setup like the following:

TV Shows
- Shows1
- Shows2
- Shows3

Will it delete files within each folder without deleted the folder - hopes this makes sense? if the item is setup as D:\TV Shows
 
You'd need to modify the script a bit to do that:

# Function to delete oldest files in the given folder until there are only 20 files left:
function Delete-To20Files
{
param ( $FolderName )
$Files = get-childitem $FolderName | where-object { $_ -is [IO.FileInfo] } | sort lastwritetime
$FileCount = $Files.Count
if ($FileCount -gt 20)
{
foreach ($File in $Files)
{
$FileCount--
$File.Delete()
if ($FileCount -le 20) { break }
}
}
}

# Call the Delete-To20Files Function for all subfolders of folder "D:\X":

get-childitem D:\X | where-object { $_ -is [IO.DirectoryInfo] } |
foreach-object { Delete-To20Files $_.FullName }