Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search in specific drive letters

Status
Not open for further replies.

EPOUSERGREECE

Technical User
Jul 25, 2005
29
GR
Hello i found the script below that searches in all the drive letters that exist on the computer. Is there any way to make it search in only specific network drive letters (f:\,r:\)?


Any help would be appreciated



<html>
<head>
<title>win-search - File Search Utility For Windows</title>
<HTA:APPLICATION ID="winsearch"
APPLICATIONNAME="win-search"
BORDER="yes"
ICON="winsearch.ico"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="yes"
SYSMENU="yes"
MAXIMIZEBUTTON="no"
WINDOWSTATE="normal"
contextmenu="no"
>

<script language="JavaScript">
/*****************************************************************
*
* Author:
* Robert Vahid Hashemian
* *
* Usage:
* win-search is a simple Windows file search utility.
* copy win-search.hta to any folder and double-click to run.
*
* Disclaimer:
* You may use this utility in any manner you wish. Credit attribution
* to author and a link to author's Web site would be appreciated.
*
* This utility comes with no guarantees of fitness. In no event
* shall the author be responsible for damages of any kind as a
* direct or indirect consequence of using this utility. User bears
* all risks.
*
******************************************************************/

var fso = new ActiveXObject("Scripting.FileSystemObject");
var totalfiles;
var totalsize;
// flag to tell user the search was incomplete only once, else recursion will cause multiples.
var searchstopalert=false;
// name of the file used as a means of control to abandon long searches.
var stophtafilename="stop-win-search.hta";
// used to hold tabulated results. can't build innerHTML in pieces as the dhtml engine tries to
// fix them by inserting tags. so we stuff this variable and then push it into div in one shot.
var fdivhtml;
var minsize;
var maxsize;
var datefrom;
var dateto;
// initialize these regexp vars. compile in expressions later
var reFile = /./;
var reKeyword = /./;

// pop up window allowing user to abort search if it takes too long
// the hta file is created on the file and executed. at the end the file is removed
// and the running app self-destructs after realizing the file's gone.
// the file is the actual indicator to continue or stop the search process. since the hta
// facility does not have native threading support (including sleep), this is the best way i could
// come up with to let user terminate a long search process.
function stopwin(a) {
if (a) {
var sr = fso.CreateTextFile(stophtafilename);
sr.Write("<html><head><title>STOP</title><HTA:APPLICATION ID=stopwinsearch contextmenu=no SINGLEINSTANCE=yes scroll=no maximizeButton=no minimizeButton=no><scr" +
"ipt language=\"JavaScript\">self.resizeTo(100,75);self.moveTo(5,5);fso=new ActiveXObject(\"Scripting.FileSystemObject\");function t(){if(!fso.FileExists(\"" + stophtafilename +
"\"))self.close();else {bb.style.backgroundColor=(bb.style.backgroundColor=='red'?'orange':'red');window.setTimeout('t()', 1000);}}function f(){if(fso.FileExists(\"" + stophtafilename +
"\"))fso.DeleteFile(\"" + stophtafilename + "\");self.close();}</scr" +
"ipt></head><body onload=\"self.focus();t()\" onunload=\"f()\" TOPMARGIN=0 LEFTMARGIN=0 MARGINWIDTH=0 MARGINHEIGHT=0><button id=\"bb\" style=\"background-color:red;font-weight:bold\" onclick=\"this.value='Stopping...'; f();\"> STOP<br>Search! </button></body></html>");
sr.Close();
shellrun(stophtafilename);
}
else {
if (fso.FileExists(stophtafilename))
fso.DeleteFile(stophtafilename);
}
}

// pop up a menu to take actions when user right clicks on item. remove it when mouse exits
// fpath is passed in escaped
function menu_on(fpath) {
// get mouse coords
var x = window.event.clientX + document.body.scrollLeft;
var y = window.event.clientY + document.body.scrollTop;

// create and display the menu layer
omenu = document.createElement("<span onmouseout=\"menu_off();\" onmouseover=\"this.style.cursor='hand';this.style.color='yellow'\" onclick=\"shellrun('notepad " +
fpath + "');this.removeNode(true);\" style=\"position:absolute;left:" +
(x-15) + ";top:" + (y-5) + ";background-color:navy;color:white;font-size:x-small;font-weight:bold\">");
omenu.innerHTML = '&nbsp;Open in Notepad&nbsp;';
document.body.insertBefore(omenu);
}

// kill the menu, if there
function menu_off() {
if (omenu != null && typeof(omenu) != "undefined")
omenu.removeNode(true);
}

// run a program.
function shellrun(s) {
var shell = new ActiveXObject("WScript.Shell");
shell.Run(unescape(s));
}

// display available drives/folders
// pass in a path to 'p' to get subfolders
function folders(p, d) {
var totaldrives=0;
var totalfolders=0;
foldiv.innerHTML = "";
// if d is true hunt for drives, else we already have the drives and we're hunting for folders.
if (d) {
dirdiv.innerHTML = "<b>Drives:</b> ";
// enumerate and display available drives
var dc = new Enumerator(fso.Drives);
for (; !dc.atEnd(); dc.moveNext())
if (dc.item().IsReady) {
// click on a drive and get the root folders
dirdiv.innerHTML += "[<span onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"folders(this.innerText, false)\">" + dc.item().RootFolder.Path + "</span>] &nbsp; ";
totaldrives++;
}
dirdiv.innerHTML += " &nbsp; <b>&lt;" + totaldrives + " Drive" + (totaldrives==1?"":"s") + "&gt;</b> or UNC path: ";
// allow user to specify unc path also
dirdiv.innerHTML += "<input title='Specify UNC path and click [SELECT]' type='text' size='10' style='font-size=xx-small;background-color:aliceblue' value='\\\\' name='uncpath'>";
// trim unc input. if blank selected send in a '*' to prompt the error message
dirdiv.innerHTML += " [<span onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"uncpath.value=uncpath.value.replace(/^\\s+|\\s+$/g, '');folders(uncpath.value==''?'*':uncpath.value, false)\">SELECT</span>] &nbsp; ";
dirdiv.innerHTML += "<br><span onmouseover=\"this.style.cursor='hand'\" style=\"position:relative; left:5px; font-weight:bold\" onclick=\"if (searchfolder.innerText=='N/A') alert('Please select a drive or folder first by clicking on it.'); else foldiv.style.display = (foldiv.style.display == 'none' ? 'block' : 'none')\">Display/Hide Folders</span>";
}
if (p != null && p != "") {
try {
var f = fso.GetFolder(p);
}
catch (e) {
alert("Sorry, unable to enumerate path.");
searchfolder.innerText = 'N/A';
return;
}
// set 'p' to be the starting subfolder to search in
searchfolder.innerText = p;
// enumerate and display subfolders
var fc = new Enumerator(f.SubFolders);
// display parent folder too, if current folder is not root
if (f.ParentFolder != null)
foldiv.innerHTML = "[ <span title=\"Click to navigate\" onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"folders(this.innerText, false)\">" + f.ParentFolder.Path + "</span> ]<br>";
for (; !fc.atEnd(); fc.moveNext()) {
// click on a folder and get the subfolders
foldiv.innerHTML += "<span title=\"Click to navigate\" onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"folders(this.innerText, false)\">" + fc.item().Path + "</span><br>";
totalfolders++;
}
foldiv.innerHTML += "<br><b>&lt;" + FormatNumberBy3(totalfolders) + " Folder" + (totalfolders==1?"":"s") + "&gt;";
}
else
alert("Welcome to win-search.\r\nClick a Drive, or specify a UNC path, and optionally click a Folder\r\nto search for files.\r\n\r\n* View source code of this program for disclaimer stuff.\r\n* }

// search folder for files based on user criteria
function fsearch(sfolder) {
var f = fso.GetFolder(sfolder);
// get a list of files
var fc = new Enumerator(f.Files);
// scan files one by one and display those that match criteria
for (; !fc.atEnd(); fc.moveNext()) {
try {
// check for size case insensitive match and file name match
if (Date.parse(fc.item().DateLastModified)>=datefrom && Date.parse(fc.item().DateLastModified)<=dateto &&
fc.item().Size >= minsize && fc.item().Size <= maxsize && reFile.test(fc.item().Name)) {
// if keyword specified, and file is empty or couldn't match keyword, then skip.
if (keyword.value!="" && (fc.item().Size==0 || !reKeyword.test(fc.item().OpenAsTextStream(1).ReadAll())))
continue;

// give some data on file when mouse over. double click runs the file. right-click launches menu.
fdivhtml += "<tr oncontextmenu=\"menu_on('" + escape('"' + fc.item().Path + '"') + "')\" title=\"" + fc.item().Name +
"\r\n\r\nCreated on: " + fc.item().DateCreated +
"\r\nModified on: " + fc.item().DateLastModified +
"\r\nLast accessed on: " + fc.item().DateLastAccessed +
"\r\n\r\n***** Double Click to launch *****\r\n***** Right Click for menu *****\" onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='default';this.style.fontWeight='bold';\" ondblclick=\"shellrun('" +
// escape to guard against character clashes inside this hideous string. file name could have squotes or spaces.
escape('"' + fc.item().Path + '"') + "')\"><td>" +
fc.item().Path + "</td><td>" + bytage(fc.item().Size) + "</td></tr>";
totalfiles++;
totalsize += fc.item().Size;
}
}
catch (e) {
//fdiv.innerHTML += fc.item().Path + " - Could Not Read !!!!<br>";
}
// see if user wants out of a long search
if (!fso.FileExists(stophtafilename)) {
// alert user on their abandoning the process. check the flag, otherwise this will pop up multiple times
// as the stack pops for each recursive call
if (!searchstopalert) {
alert("Search stopped by user. Results are incomplete.");
searchstopalert = true;
}
return;
}
} // for
if (!fso.FileExists(stophtafilename)) {
if (!searchstopalert) {
alert("Search stopped by user. Results are incomplete.");
searchstopalert = true;
}
return;
}
// user wants deep search. go inside subfolders recursively.
if (recurse.checked) {
var f2 = fso.GetFolder(sfolder);
var fc2 = new Enumerator(f2.SubFolders);
for (; !fc2.atEnd(); fc2.moveNext())
fsearch(fc2.item().Path);
}
}

// run this when user clicks on "search"
function gosearch() {
minsize = parseInt(fminsize.value.replace(/\D/g, ""));
maxsize = parseInt(fmaxsize.value.replace(/\D/g, ""));

// set reasonable values for default min and max file sizes, unless valid values specified.
if (isNaN(minsize))
minsize = 0;
if (isNaN(maxsize))
maxsize = 10000000000;

datefrom = Date.parse(dfrom.value);
dateto = Date.parse(dto.value);

// set reasonable values for default from and to dates, unless valid values specified.
if (isNaN(datefrom))
datefrom = Date.parse("Jan 1, 1970");
if (isNaN(dateto))
dateto = Date.parse("Jan 1, 2070");
if (datefrom>dateto) {
datefrom = Date.parse("Jan 1, 1970");
dateto = Date.parse("Jan 1, 2070");
}

// escape all puncs so they're processed literally. this might be too general and cause some problems.
// compile for better performance.
reFile.compile(fpattern.value.replace(/(\W)/g, "\\$1"), "i");
reKeyword.compile(keyword.value.replace(/(\W)/g, "\\$1"), (casebox.checked ? "i" : ""));

sfolder = searchfolder.innerText;
if (sfolder == "N/A" || sfolder == "" || sfolder == null) {
alert("Please select a drive or folder first by clicking on it.");
return;
}
// display info in a table
fdivhtml="<table width=100% border=1 cellpadding=0 cellspacing=0 style=\"font-size:x-small;\"><thead style=\"font-weight:bold;background-color:wheat\"><tr><td width=90%>File</td><td>Size</td></tr></thead><tbody>";
totalfiles=totalsize=0;
searchstopalert=false;
// pop up a window to allow user to abandon
stopwin(true);
// let user know what's happening, meanwhile give hta stop window a chance to situate itself.
alert('A popup was created to let you terminate\r\nthe search if it takes too long.\r\n\r\nClick OK to continue.');
// start digging
fsearch(searchfolder.innerText);

fdivhtml += "<tfoot style=\"font-weight:bold;background-color:lightgrey\"><tr><td>" + FormatNumberBy3(totalfiles) +
" File" + (totalfiles==1?"":"s") + "</td><td>" + bytage(totalsize) + "</td></tr></tfoot></tbody></table>";
fdiv.innerHTML = fdivhtml;
if (!searchstopalert)
alert('Done.');
// function causes weirdness if called directly when search list is short, because the hta stop file
// is deleted as it tries to launch. so this delay gives the process enough time to act sanely.
// the alert call above takes care of this now.
// window.setTimeout("stopwin(false)", 1000);
stopwin(false);
}

// pulled from: function FormatNumberBy3(num, decpoint, sep) {
// check for missing parameters and use defaults if so
if (arguments.length == 2) {
sep = ",";
}
if (arguments.length == 1) {
sep = ",";
decpoint = ".";
}
// need a string for operations
num = num.toString();
// separate the whole number and the fraction if possible
a = num.split(decpoint);
x = a[0]; // decimal
y = a[1]; // fraction
z = "";


if (typeof(x) != "undefined") {
// reverse the digits. regexp works from left to right.
for (i=x.length-1;i>=0;i--)
z += x.charAt(i);
// add seperators. but undo the trailing one, if there
z = z.replace(/(\d{3})/g, "$1" + sep);
if (z.slice(-sep.length) == sep)
z = z.slice(0, -sep.length);
x = "";
// reverse again to get back the number
for (i=z.length-1;i>=0;i--)
x += z.charAt(i);
// add the fraction back in, if it was there
if (typeof(y) != "undefined" && y.length > 0)
x += decpoint + y;
}
return x;
}

// render file size in conventional format
function bytage(s) {
var b = [" Byte", " KB", " MB", " GB", " TB"];
var i = 0;
// keep dividing until we get below 1k
for(; i<5; i++) {
if (s>1024)
s/=1024;
else
break;
}
// return number in more legible format. if number is whole, don't mess with it, else round after the
// second decimal point, stuff into a number to drop trailing 0's, and add an "s" if the size will
// be in bytes but not 1.
return FormatNumberBy3(new Number(s==Math.ceil(s)?s:s.toFixed(2))) + b + (i==0?(s==1?"":"s"):"");
}

// initial date values
function init_dates() {
/*
var monthstr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dt = new Date();
dto.value = monthstr[dt.getMonth()] + " " + dt.getDate() + ", " + dt.getFullYear();
// go back about 10 years. don't do dt.setFullYear(dt.getFullYear() - 5)
// because leap year could bite on feb 29.
dt = new Date(dt.valueOf() - 1000*3600*24*3650);
dfrom.value = monthstr[dt.getMonth()] + " " + dt.getDate() + ", " + dt.getFullYear();
*/
dfrom.value = "Jan 1, 1970";
dto.value = "Jan 1, 2070";
}

</script>
</head>

<body bgcolor="#FFFFF9" onload="self.moveTo(100,100);init_dates();folders(null, true);">
<h1 align="center"><a title=" target="_blank" href=" - File Search Utility For Windows</h1>
<div style="background-color:palegreen;font-size:x-small;" id="dirdiv"></div>
<div style="background-color:ivory;font-size:x-small;display:none" id="foldiv"></div><p>
Folder: <span style="background-color:pink;font-weight:bold;font-size:x-small" id="searchfolder">N/A</span>
&nbsp; <input style="background-color:ivory;" type="checkbox" name="recurse"> <font style="font-size:x-small">Search Subfolders</font><br>
File Pattern: <input title="Partial names are okay. Do not use wildcards." style="background-color:ivory;font-size:x-small" type="text" name="fpattern"><br>
Keyword: <input title="Partial names are okay. Do not use wildcards." style="background-color:ivory;font-size:x-small" type="text" name="keyword">
&nbsp; <input style="background-color:ivory;" type="checkbox" name="casebox" checked> <font style="font-size:x-small">Ignore Case</font><br>
File Size Between <input style="background-color:ivory;font-size:x-small" type="text" name="fminsize" value="0" size="10"> and
<input style="background-color:ivory;font-size:x-small" type="text" name="fmaxsize" value="10000000000" size="10"> Bytes<br>
File Created/Modified Between <input style="background-color:ivory;font-size:x-small" type="text" name="dfrom" size="10"> and
<input style="background-color:ivory;font-size:x-small" type="text" name="dto" size="10">
<p>
&nbsp; <button style="border:3 solid navy;background-color:lightblue;font-size:x-small" onclick="gosearch();">Search</button>
<button style="position:absolute;left:580;top:120;background-color:red;font-weight:bold;font-size:medium;height:50" onclick="self.close()"> E X I T </button>
<p>
<div style="background-color:antiquewhite;font-size:x-small;" id="fdiv"></div>
</body>
</html>
 
1.- This will only work for IE and low security settings.
2.- Don't expect many poeple to read all that code.

Cheers,
Dian
 
As a complete guess, inside the "folders" function, after this line:

Code:
if (dc.item().IsReady) {

you could add this:

Code:
var driveLetter = dc.item.DriveLetter.toLowerCase();
if (driveLetter != 'f' && driveLetter != 'r') continue;

Hope this helps,
Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
I have tried to alter the code but with no result. I know that the problem is in this area of code :


// display available drives/folders
// pass in a path to 'p' to get subfolders
function folders(p, d) {
var totaldrives=0;
var totalfolders=0;
foldiv.innerHTML = "";
// if d is true hunt for drives, else we already have the drives and we're hunting for folders.
if (d) {
dirdiv.innerHTML = "<b>Drives:</b> ";
// enumerate and display available drives
var dc = new Enumerator(fso.Drives);
for (; !dc.atEnd(); dc.moveNext())
if (dc.item().IsReady) {
// click on a drive and get the root folders
dirdiv.innerHTML += "[<span onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"folders(this.innerText, false)\">" + dc.item().RootFolder.Path + "</span>] &nbsp; ";
totaldrives++;
}



but since there is a loop (i am not familiar with hta code) it is difficult for me to change it in order get only the specific drive letters and not all the drive letters that i have on my my computer.


Thank you very much for your help.
 
I am sorry for not replying but i and my partner were trying to figure out what is going on.

We have included the two lines (2---> and 3--->) inside the loop folder but now we have a script error that says
Error:'Item.DriveLetter' is null or not an object. Then if you press 'No' to debug you have only the choice of C Drive.
No matter If you change the letters (D or X) you have the same result.
If we insert the two lines after the line 1---> then the script is not work and you don't have nothing of drive to choice
in the line where we click the drives.





// display available drives/folders
// pass in a path to 'p' to get subfolders
function folders(p, d) {
var totaldrives=0;
var totalfolders=0;
foldiv.innerHTML = "";
// if d is true hunt for drives, else we already have the drives and we're hunting for folders.
if (d) {
dirdiv.innerHTML = "<b>Drives:</b> ";
// enumerate and display available drives
var dc = new Enumerator(fso.Drives);
for (; !dc.atEnd(); dc.moveNext())
1---> if (dc.item().IsReady) {
// click on a drive and get the root folders
dirdiv.innerHTML += "[<span onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"folders(this.innerText, false)\">" + dc.item().RootFolder.Path + "</span>] &nbsp; ";
totaldrives++;
2---> var driveLetter = dc.item.DriveLetter.toLowerCase();
3---> if (driveLetter != 'D' && driveLetter != 'X') continue;
}
dirdiv.innerHTML += " &nbsp; <b>&lt;" + totaldrives + " Drive" + (totaldrives==1?"":"s") + "&gt;</b> or UNC path: ";
// allow user to specify unc path also
dirdiv.innerHTML += "<input title='Specify UNC path and click [SELECT]' type='text' size='10' style='font-size=xx-small;background-color:aliceblue' value='\\\\' name='uncpath'>";
// trim unc input. if blank selected send in a '*' to prompt the error message
dirdiv.innerHTML += " [<span onmouseout=\"this.style.fontWeight='';\" onmouseover=\"this.style.cursor='hand';this.style.fontWeight='bold';\" onclick=\"uncpath.value=uncpath.value.replace(/^\\s+|\\s+$/g, '');folders(uncpath.value==''?'*':uncpath.value, false)\">SELECT</span>] &nbsp; ";
dirdiv.innerHTML += "<br><span onmouseover=\"this.style.cursor='hand'\" style=\"position:relative; left:5px; font-weight:bold\" onclick=\"if (searchfolder.innerText=='N/A') alert('Please select a drive or folder first by clicking on it.'); else foldiv.style.display = (foldiv.style.display == 'none' ? 'block' : 'none')\">Display/Hide Folders</span>";
}

any help ?




 
I guess following the syntax you've used everywhere else might make a difference, so try using "item()" instead of "item".

While this might have been a typo in my original suggestion, you've coded all of this so far, so am surprised you hadn't tried that as a simple debugging step.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Dan,

i tried it but now i get 0 drives when i put the command lines after

if (dc.item().IsReady) {

and if i put it after the line

totaldrives++;

i get all the drives.


Do you have any other suggestions?
 
There is no alert or script errors. Does it work on your computer?


 
Yes. It works perfectly if you use the code in my original post with the typo corrected as per my previous post.

This assumes that what you're trying to do is to remove drives from appearing in the list that users can select from.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Could you please copy and paste the entire code? I can' t be that wrong.


Thank you
 
The [!]exact[/!] steps I took are:

1. Copied your code as posted in your original post.
2. Saved it as "c:\driveTest.html"
3. Searched for the exact line I mentioned in my first post
4. Pasted in the exact code I mentioned in my first post
5. Fixed the exact typo I mentioned in my fifth post, so replaced:
Code:
dc.item.DriveLetter.toLowerCase()
with:
Code:
dc.item().DriveLetter.toLowerCase()

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Thank you very much BillyRayPreachersSon. The script now works superb.

Is there any way you can tell me how to display the searched files while the search is in progress and not to wait until the end?


If you could help me i would appreciate it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top