Change a script to check remaining space of a drive - vbscript

I currently have this VBScript, which checks the size of a folder, then deletes files (oldest first) until a threshold is reached.
Option Explicit
'use next line for production
On Error Resume Next
'use next line for debugging
'On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim objFSO, strOldestFile, dtmOldestDate, strFolder, oFolder, intFolderSize
Set objFSO = CreateObject("Scripting.FileSystemObject")
dtmOldestDate = Now
strFolder = "C:\Users\PLEX\Downloads\Torrent\"
strOldestFile = ""
Set oFolder = objFSO.GetFolder(strFolder)
intFolderSize = Int(((oFolder.Size / 1024) / 1024) / 1024)
Do While intFolderSize >= 110
strOldestFile = ""
dtmOldestDate = Now
FindOldestFile oFolder
'WScript.Echo strOldestFile
objFSO.DeleteFile strOldestFile, True
strResult = strResult & vbNewLine & dtmOldestDate & vbTab & strOldestFile
intFolderSize = Int(((oFolder.Size / 1024) / 1024) / 1024)
Loop
'WScript.Echo strResult
WScript.Quit
Sub FindOldestFile(objFolder)
Dim objFile, colFiles, colFolders, strFile, dtmFileDate
'find oldest file
Set colFiles = objFolder.Files
For Each objFile In colFiles
strFile = objFile.Path
dtmFileDate = objFile.DateCreated
If dtmFileDate < dtmOldestDate Then
dtmOldestDate = dtmFileDate
strOldestFile = strFile
End If
Next
'recurse subfolders
Set colFolders = objFolder.SubFolders
For Each objFile In colFolders
FindOldestFile objFile
Next
End Sub
Currently this script will:
Check the capacity of folder A including all subfolders.
Delete files (oldest first) from folder A and subfolders until a threshold is reached (in this case, 110GB)
I'd like to modify the script to do this:
Check the capacity of folder A including all subfolders.
Delete files (oldest first) from folder B (which is a subfolder of folder A) and subfolders until a threshold is reached.
For example, is it possible to get this script to check the used capacity of the entire C: drive and delete the oldest files from C:\Users\PLEX\Downloads\Torrent\ when there is less than 5% remaining on C:?
Edit: I already had full access, and fixed the error by changing C:\ to C: . I also changed C:\Users\PLEX\Desktop\New Folder to \Users\PLEX\Desktop\New Folder and am now getting no errors. The only problem is that IntFolderSize still shows the size of my subfolder, not the root. I've confirmed that by using Wscript.Echo intfoldersize. My current script is below. How can I get IntFolderSize to show the used size of the root?
option explicit
'use next line for production
'On Error Resume Next
'use next line for debugging
'On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim objFSO, strOldestFile, dtmOldestDate, strFolder, oFolder, intFolderSize
Set objFSO = CreateObject("Scripting.FileSystemObject")
dtmOldestDate = Now
strFolder = "C:"
strOldestFile = ""
Set oFolder = objFSO.GetFolder( strFolder)
intFolderSize = Int(((oFolder.Size / 1024) / 1024) / 1024)
Wscript.Echo intfoldersize
Do While intFolderSize >= 70
strOldestFile = ""
dtmOldestDate = Now
FindOldestFile objFSO.GetFolder(objFSO.BuildPath(strFolder,"\Users\PLEX\Desktop\New Folder\"))
'wscript.echo strOldestFile
objFSO.DeleteFile strOldestFile, True
strResult = strResult & vbNewLine & dtmOldestDate & vbTab & strOldestFile
intFolderSize = Int(((oFolder.Size / 1024) / 1024) / 1024)
Loop
'Wscript.Echo strResult
Wscript.Quit
Sub FindOldestFile( objFolder)
Dim objFile, colFiles, colFolders, strFile, dtmFileDate
' find oldest file
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFile = objFile.Path
dtmFileDate = objFile.DateCreated
If dtmFileDate < dtmOldestDate Then
dtmOldestDate = dtmFileDate
strOldestFile = strFile
End If
Next
' recurse subfolders
Set colFolders = objFolder.SubFolders
For Each objFile in colFolders
FindOldestFile objFile
Next
End Sub

Change
FindOldestFile oFolder
into
FindOldestFile objFSO.GetFolder(objFSO.BuildPath(strFolder, "sub\folder"))
where strFolder is your root folder and "sub\folder" the relative path to the subfolder below that root folder.
Edit: Note that the oFolder.Size property will raise an error unless you have access to every single file and folder below oFolder. If you want to check the free diskspace on the volume anyway, you may be better off using WMI for that and using oFolder strictly for the folder you want to delete from:
strFolder = "C:\Users\PLEX\Desktop\New folder"
Set oFolder = objFSO.GetFolder(strFolder)
threshold = ... 'desired minimum free diskspace in byte
Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_Volume WHERE DriveLetter='C:'"
Do While wmi.ExecQuery(qry).ItemIndex(0).FreeSpace < threshold
...
FindOldestFile oFolder
...
Loop

Related

Getting the Folder size for only subfolders, whist ignoring any other content?

I’ve created the script below, which manages and maintains allocated storage within a RootFolder, into which are stored daily backups each within its sown individual folder, and should the RootFolder content exceed a preset limit, then the oldest backup folder is then deleted.
So far so good . . . the problem I have is that largeish files may also be added to the RootFolder [strHomeFolder] and as such are also included in the total accumulated 'size'. As a consequence the backup folders may be prematurely deleted, and in the worst case scenario all may be deleted altogether, which unfortunately may somewhat defeat the purpose of having backups !
I am therefore seeking advice in makeing the objFSO.GetFolder check only the contents of all of the backup Folders located within the RootFolder whilst ignoring any of the files at that level.
strOldestFolder = ""
dtmOldestDate = Now
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%\HDBackups")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strHomeFolder)
intFolderSize = Int((objFolder.Size / 1024) / 1024)
If intFolderSize >= 50 Then ' change as appropriate value in MBytes
Set objSubFolders = objFolder.SubFolders
For Each objFolder in objSubFolders
strFolder = objFolder.Path
dtmFolderDate = objFolder.DateCreated
If dtmFolderDate < dtmOldestDate Then
dtmOldestDate = dtmFolderDate
strOldestFolder = strFolder
End If
Next
objFSO.DeleteFolder(strOldestFolder)
End If
Just loop through the Root folder's SubFolders and sum up intFolderSize:
strOldestFolder = ""
dtmOldestDate = Now
Set objShell = CreateObject("WScript.Shell")
strHomeFolder = objShell.ExpandEnvironmentStrings("%USERPROFILE%\HDBackups")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strHomeFolder)
Dim objSubFolder
intFolderSize = 0
For Each objSubFolder In objFolder.SubFolders
intFolderSize = intFolderSize + objSubFolder.Size
Next
intFolderSize = Int((intFolderSize / 1024) / 1024)
If intFolderSize >= 50 Then ' change as appropriate value in MBytes
Set objSubFolders = objFolder.SubFolders
For Each objFolder In objSubFolders
strFolder = objFolder.Path
dtmFolderDate = objFolder.DateCreated
If dtmFolderDate < dtmOldestDate Then
dtmOldestDate = dtmFolderDate
strOldestFolder = strFolder
End If
Next
objFSO.DeleteFolder (strOldestFolder)
End If

Copying files from source folder to target folder

Hi I'm trying to copy a file from source to target folder. But I'm getting an error "Bad File name or number" when im running it.
Here is my code:
Option Explicit
Dim srcFolder, trgFolder
srcFolder = "\\sunpowercorp.com\spap\SPMM-QA\Public-Read_Write\SPMM QA Documents\Dominic Yumul\Toshiba Monthly Quality Report"
trgFolder = "http:\\dms\departments\QUALITY\Quality Ops in the Box\Quality Ops in the Box library\025 SPMM QA Staff Documents\Toshiba Monthly Quality Report"
CopyFilesAndFolders srcFolder, trgFolder
WScript.Quit
Sub CopyFilesAndFolders(ByVal strSource, ByVal strDestination)
Dim ObjFSO, ObjFolder, ObjSubFolder, ObjFile, files
Dim TargetPath
Set ObjFSO = CreateObject("scripting.filesystemobject")
'connecting to the folder where is going to be searched
Set ObjFolder = ObjFSO.GetFolder(strSource)
TargetPath = Replace (objFolder.path & "\", strSource, strDestination,1,-1,vbTextCompare)
If Not ObjFSO.FolderExists (TargetPath) Then ObjFSO.CreateFolder (TargetPath)
Err.clear
On Error Resume Next
'Check all files in a folder
For Each objFile In ObjFolder.files
If Err.Number <> 0 Then Exit For 'If no permission or no files in folder
On Error goto 0
If CheckToCopyFile (objFile.path, TargetPath & "\" & objFile.name) Then
objFSO.copyfile objFile.path, TargetPath & "\" & objFile.name, True
End If
Next
'Recurse through all of the subfolders
On Error Resume Next
Err.clear
For Each objSubFolder In ObjFolder.subFolders
If Err.Number <> 0 Then Exit For 'If no permission or no subfolder in folder
On Error goto 0
'For each found subfolder there will be searched for files
CopyFilesAndFolders ObjSubFolder.Path & "\", TargetPath & ObjSubFolder.name & "\"
Next
Set ObjFile = Nothing
Set ObjSubFolder = Nothing
Set ObjFolder = Nothing
Set ObjFSO = Nothing
End Sub
Function CheckToCopyFile(ByVal strSourceFilePath, ByVal strDestFilePath)
Dim oFSO, oFile, SourceFileModTime, DestFileModTime
CheckToCopyFile = True
Set oFSO = CreateObject("scripting.filesystemobject")
If Not oFSO.FileExists (strDestFilePath) Then Exit Function
Set oFile = oFSO.GetFile (strSourceFilePath)
SourceFileModTime = oFile.DateLastModified
Set oFile = Nothing
Set oFile = oFSO.GetFile (strDestFilePath)
DestFileModTime = oFile.DateLastModified
Set oFile = Nothing
If SourceFileModTime =< DestFileModTime Then CheckToCopyFile = False
Set oFSO = Nothing
End Function
I do not know what line I am getting the error.
On Windows Vista and newer you should be able to map SharePoint libraries to drive letters using WebDAV as described in this blog post:
Set net = CreateObject("WScript.Network")
net.MapNetworkDrive "X:", "\\sp.example.org#SSL\site\Shared Documents\"
Then copy your files to the mapped drive using FileSystemObject methods.

VBS to list file names NOT matching given extension

I have been working on the following VBS. This will search a parent folder and all child / subfolders and print any file with the provided extension (doc, docx, msg, ppt, txt) and came up with the following. I am new to VBS but I would like to define the file extensions to IGNORE, listing all others. I have the directory listing of each file type working but I don't want to have to set a NEXT for each file type. I was able to use the <> code in the top section to show all files that don't match an extension using:
If objFSO.GetExtensionName(strFileName) <> "jpg" then
But this doesn't work in the lower part:
if LCase(InStr(1,Files, "jpg")) > 1 then Wscript.Echo Files
I would also like to be able to define multiple file types; like
If objFSO.GetExtensionName(strFileName) <> "jpg" OR "jpeg" OR "tiff"
Lastly I need to output to a text file, not a windows script msg box.
Can anyone help? Sorry for typos or confusion, English is not my first language.
Dim fso
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set FSO = WScript.CreateObject("Scripting.Filesystemobject")
Set f = fso.CreateTextFile("C:\temp\output.txt", 2)
objStartFolder = "C:\Test"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "x937" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "docx" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "doc" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "txt" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "msg" then
Wscript.Echo objFile.Name
End If
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "msg")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "txt")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "ppt")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "xls")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "doc")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
End Sub
You can check all of the extensions in one loop:
For Each objFile in colFiles
Dim strFileName : strFileName = objFile.Name
Dim strExtension : strExtension = LCase(objFSO.GetExtensionName(strFileName))
If strExtension <> "txt" And _
strExtension <> "jpg" And _
strExtension <> "msg" And _
strExtension <> "docx" Then
Wscript.Echo objFile.Name
End If
Next
I just put a bunch of random extensions in because it wasn't clear which ones you want to ignore. Make sure you put them all in lowercase so the comparison works because the code converts the actual extension to lowercase.
For exporting the output to a txt file, the below code might work
Function TextFile_Generate()
strFile = "C:\...\ReportName.txt"
strValue = "output text..."
Set objFSO=CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strFile) Then
Set objFile = objFSO.OpenTextFile(strFile,8, True)
Else
Set objFile = objFSO.CreateTextFile(strFile,True)
End If
objFile.Write strValue & vbCrLf
objFile.Close
Set objFile = Nothing
Set objFSO =Nothing
End Function

d: \ learning \ vbs \ backup3.vbs (32, 1) Runtime Error Microsoft VBScript: Path not found

When I am running script, I am getting error, I can not understand why.
The error is:
d:\learning\vbs\backup3.vbs (32, 1)Runtime Error Microsoft VBScript: Path not found.
Error in this string: Set objFolder = objFSO.GetFolder(str)
My code:
Option Explicit
Dim objFSO
Dim objShell
Dim objFolder
Dim sourceDir
Dim destDir
Dim rar
Dim n
sourceDir = "d:\learning\vbs\TBack"
destDir = "\\LILO\Users\monorels\Music\Backup"
rar = "d:\learning\vbs\Rar.exe"
n = 3
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run """rar"" a -agYYYY-MM-DD-HH-MM-SS " & destDir & " " & sourceDir
search_delete "\\LILO\Users\monorels\Music\Backup", n
Sub search_delete(str, n)
Dim strOldestFile, dtmOldestDate
Dim count
Dim intFolderSize
Dim objFolder
Dim colFiles
Dim strFile
Dim delFile
Dim fso
strOldestFile = ""
dtmOldestDate = Now
Set objFolder = objFSO.GetFolder(str)
Set colFiles = objFolder.Files
Do
count = 0
For Each objFile In colFiles
count = count + 1
strFile = objFile.Path
dtmFileDate = objFile.DateCreated
If dtmFileDate < dtmOldestDate Then
dtmOldestDate = dtmFileDate
strOldestFile = strFile
End If
Next
objFSO.DeleteFile (strOldestFile)
Loop Until count > n
End Sub
Help me, please.

Copy and rename oldest file using vbs

Hello again everybody!
I've been digging into .vb and .vbs. I have a small problem concerning renaming a file after copying it. From this (just giving credit where credit is due :p) person I've found how to copy the file to another folder, however I seem not to have been able to rename the file.
So I want to copy the file and rename the original to execute.HMS
This is the code for copying:
Set objFSo = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("F:\commandfolder")
Set colFiles = objFolder.Files
dtmOldestDate = Now
For Each objFile in colFiles
If objFile.DateCreated < dtmOldestDate Then
dtmOldestDate = objFile.DateCreated
strOldestFile = objFile.Path
End If
Next
objFSO.CopyFile strOldestFile, "F:\commandfolder\Processed\"
Thanks in advance and kind regards,
Dave
VBScript doesn't provide a rename method for files. You have to use MoveFile instead:
objFSO.CopyFile strOldestFile, "F:\commandfolder\Processed\"
objFSO.MoveFile strOldestFile, objFSO.GetParentFolderName(strOldestFile) & "\execute.HMS"
A better option might be remembering the file object instead of just its path and then using the object's methods:
For Each objFile in colFiles
If objFile.DateCreated < dtmOldestDate Then
dtmOldestDate = objFile.DateCreated
Set oldestFile = objFile
End If
Next
oldestFile.Copy "F:\commandfolder\Processed\"
oldestFile.Name = "execute.HMS"
Based on this answer to a 'find' problem, I added code to move the file by using the file's Move method:
Const csSrcF = "..\testdata\17806396"
Const csDstF = "..\testdata\17806396\dst\"
Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
Dim oLstPng : Set oLstPng = Nothing
Dim oFile
For Each oFile In goFS.GetFolder(csSrcF).Files
If "png" = LCase(goFS.GetExtensionName(oFile.Name)) Then
If oLstPng Is Nothing Then
Set oLstPng = oFile ' the first could be the last
Else
If oLstPng.DateLastModified < oFile.DateLastModified Then
Set oLstPng = oFile
End If
End If
End If
Next
If oLstPng Is Nothing Then
WScript.Echo "no .png found"
Else
WScript.Echo "found", oLstPng.Name, oLstPng.DateLastModified
oLstPng.Move csDstF
If goFS.FileExists(goFS.BuildPath(csDstF, oLstPng.Name)) Then
WScript.Echo "Moved."
Else
WScript.Echo "Not moved."
End If
End If
This is my working solution (it's edited to the context but you'll figure it out if you need it :))
Set obj = CreateObject("Scripting.FileSystemObject")
Set objFSo = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("F:\commandfolder")
Set colFiles = objFolder.Files
dtmOldestDate = Now
For Each objFile in colFiles
If objFile.DateCreated < dtmOldestDate Then
dtmOldestDate = objFile.DateCreated
strOldestFile = objFile.Path
End If
Next
objFSO.CopyFile strOldestFile, "F:\commandfolder\Processed\"
obj.DeleteFile("F:\commandfolder\Action\execute.hms")
objFSO.MoveFile strOldestFile, "F:\commandfolder\Action\execute.hms"

Resources