Copying Files Without Overwrite in JScript
Yeah, I know. JScript is the bane of my existence. It’s really a cool scripting language, but NO ONE USES IT. I’ve spent days trying to convert some code from VBScript to JScript because no one cared enough to write it out in the first place. Today I’ve written a function that allows you to copy the contents of one folder to another without overwriting existing files of the same name at the destination. I’m having to install some old software on a few user’s computers but all they really need are the OCX and DLL files, so we got those put into a common folder. Since these files are old (not touched since at least 1998), we don’t want to overwrite newer files of the same name. There’s no batch command that I can find that will do it, so I wrote a script that looks through the files of the source and compares them one by one to the destination, copying unmatched files to the destination. Here’s the code:
function CopyFiles(SourceFolder, TargetFolder, Overwrite) {
var objFSO = WScript.CreateObject("Scripting.FileSystemObject");
var count = 0;
// handle optional variables
if(Overwrite == null) {
Overwrite = false;
}
if(SourceFolder.substr(SourceFolder.length - 1, 1) != "\\") {
SourceFolder = SourceFolder + "\\";
}
if(TargetFolder.substr(TargetFolder.length - 1, 1) != "\\") {
TargetFolder = TargetFolder + "\\";
}
if(!objFSO.FolderExists(TargetFolder)) {
objFSO.CreateFolder(TargetFolder);
}
var FileNames = new Enumerator(objFSO.GetFolder(SourceFolder).Files);
for(;!FileNames.atEnd();FileNames.moveNext()) {
// check to see if the current file exists at destination
if((objFSO.FileExists(TargetFolder + FileNames.item().Name) && Overwrite) || !objFSO.FileExists(TargetFolder + FileNames.item().Name)) {
objFSO.CopyFile(SourceFolder + FileNames.item().Name, TargetFolder + FileNames.item().Name);
count++;
}
}
return count;
}
Now, it does allow overwriting if you need it to, but it assumes you don’t. Also it doesn’t handle subfolders. It wouldn’t be too hard to add a for loop that uses the Subfolders collection from the Folder object and then call the function recursively, but I don’t need to do that. Hope this helps someone out there.