#Windows powershell script to move files based on free space
$drive_need = 150 #target D space minimum in GB
$server_need = 200 #target Server space minimum in GB
$tv_folder1 = "D:\Recorded TV"
$tv_folder2 = "\\Server\Recorded TV"
$File ="D:\TVmovelog.txt" #log file
$drive_free = (get-WMIObject win32_LogicalDisk -filter "DeviceID='D:'"| ForEach-Object {[math]::round($_.freespace / 1GB)})
$server_free = (get-WMIObject win32_LogicalDisk -filter "DeviceID='Y:'"| ForEach-Object {[math]::round($_.freespace / 1GB)})
Get-Date | Out-File $File -append
if ($drive_free -gt $drive_need) # If there is enough space, do nothing
{
write-output ("D: has $drive_free GB of free space - aborted file moving") | out-file $file -append
exit
}
if ($server_free -lt $server_need) # If the sever doesn't have enough room, just send a warning email, then stop
{
write-output ("Not enough free space - aborted file moving") | out-file $file -append
$EmailFrom = "EMAILADDYHERE@gmail.com"
$EmailTo = "EMAILADDYHERE@gmail.com"
$Subject = "Notification from HTPC"
$Body = "The server has less than $server_need GB of disk space"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAILUSRNAME", "GMAILPASS");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
exit
}
While ($drive_need -gt $drive_free) # As long as D: space is less than needed, move the oldest WTV file and its associated log file
{
try
{
$move_file = dir $tv_folder1 *.wtv | sort lastwritetime | select -first 1 # Get the name of the oldest WTV file
copy-item $move_file $tv_folder2
$move_log = $move_file -replace ".wtv$", ".log" # convert to log file name
$move_log = dir $tv_folder1 $move_log # Get the name of the oldest log file
copy-item $move_log $tv_folder2
write-output ("Successfully copied $move_file") | out-file $file -append
}
catch # watch for error, don't delete file(s) is there is an error (I have no idea if this trapping works)
{
write-output ("Could not copy file - aborted") | out-file $file -append
exit
}
remove-item $move_file #Not necessary for ME to remove the log too, since it's disapearing on its own. Could be showanalzer cleaning up.
#remove-item $move_log
write-output ("Successfully deleted $move_file and $move_log") | out-file $file -append
$drive_free = (get-WMIObject win32_LogicalDisk -filter "DeviceID='D:'"| ForEach-Object {[math]::round($_.freespace / 1GB)})
}