VBScript to find a file and reports its location and size?

MikeLyons74
MikeLyons74 used Ask the Experts™
on
I am looking to create a VBscript that can search the local machine and report they location of a file and its size.  Output needs to be CSV file.  Your help is very much appreciated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Paste the script below into a text file with a .vbs extension.  Customize the value of the strFileName variable on line 4 with the name of the file to search for.  Running the script will search all local hard drives and write output to a comma-delimited text file.


Const intkB = 1024

strComputer = "."
strFileName = "filename.txt"
strReport = "report.csv"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReport = objFSO.CreateTextFile(strReport, True)
objReport.WriteLine "File,Size (kB)"

For Each strDrive In LocalHardDrives(strComputer)
    For Each strFile In DirToArray(strDrive, strFileName, True)
        Set objFile = objFSO.GetFile(strFile)
        strSize = Round(objFile.Size/intkB, 2)
        objReport.WriteLine Chr(34) & strFile & Chr(34) & "," & strSize
    Next
Next

objReport.Close
WScript.Echo "Query complete."

Function LocalHardDrives(strTargetComputer)
    Set objWMIService = GetObject("winmgmts:\\" & strTargetComputer &_
        "\root\CIMV2")
    Set colItems = objWMIService.ExecQuery("SELECT DeviceID FROM " &_
        "Win32_LogicalDisk WHERE DriveType = 3")

    intLimit = 0

    For Each objItem In colItems
        ReDim Preserve arrResults(intLimit)
        arrResults(intLimit) = objItem.DeviceID
        intLimit = intLimit + 1
    Next
    
    LocalHardDrives = arrResults
End Function

Function DirToArray(strRootFolder, strFileMask, blnRecurse)
    strCommand = "%comspec% /c @dir " & Chr(34) &_
        strRootFolder & "\" & strFileMask & Chr(34) & " /a:-d /b"
        
    If blnRecurse Then
        strCommand = strCommand & " /s"
    End If

    Set objShell = CreateObject("WScript.Shell")
    Set objWshScriptExec = objShell.Exec(strCommand)
    Set objStdOut = objWshScriptExec.StdOut
    
    intOutputLimit = 0

    Do Until objStdOut.AtEndOfStream
        strFilePath = objStdOut.ReadLine
        
        If Not blnRecurse Then
            strFilePath = strRootFolder & "\" & strFilePath
        End If
        
        ReDim Preserve arrOutput(intOutputLimit)
        arrOutput(intOutputLimit) = strFilePath
        intOutputLimit = intOutputLimit + 1
    Loop
    
    DirToArray = arrOutput
End Function

Open in new window

Author

Commented:
Awesome, thank you so much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial