VBScript to find and move files automatically - vbscript

I've been tasked with trying to automate a task at work, because we've had issues lately with people remembering to do it.
In general, here's what I need a script to do:
Get the date of the previous day, in the format YYYYMMDD
Enter a folder with that given name
Search within all the folders underneath that location for 4 specific files
Copy those files to several different locations
The issue I'm having is that, for the 4 files I'm looking for, they're located in 2 different folders. 3 in 1, 1 in the other. The names of these folders changes daily, depending on what queue they got put into when generated by some other software. I need these files to be moved so that another script can be run on them. I'm having trouble figuring out how to accomplish this. Anyone have some ideas?

If the folders containing the interesting files are subfolders of your dated directory, you can use a nested loop:
Dim sDFolder : sDFolder = "..\data\20110105"
Dim dicFiNa : Set dicFiNa = CreateObject("Scripting.Dictionary")
dicFiNa("1.txt") = ""
dicFiNa("3.txt") = ""
dicFiNa("5.txt") = ""
Dim oRDir : Set oRDir = goFS.GetFolder(sDFolder)
Dim oSDir
For Each oSDir In oRDir.SubFolders
Dim oFile
For Each oFile In oSDir.Files
WScript.Echo "looking at", oFile.Path
If dicFiNa.Exists(oFile.Name) Then
WScript.Echo "found", oFile.Name, "will copy"
End If
Next
Next
output:
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\6.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\5.txt
found 5.txt will copy
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\4.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\3.txt
found 3.txt will copy
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\2.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\1.txt
found 1.txt will copy
A full recursive walk would be a bit more complex, so say so, if you need it.
Just for fun: a recursive version:
Dim sDFolder : sDFolder = "..\data\20110105"
Dim dicFiNa : Set dicFiNa = CreateObject("Scripting.Dictionary")
dicFiNa("1.txt") = ""
dicFiNa("3.txt") = ""
dicFiNa("55.txt") = ""
Dim oRDir : Set oRDir = goFS.GetFolder(sDFolder)
walk oRDir, dicFiNa, "whatever you need to copy the files"
Sub walk(oDir, dicFiNa, vCargo)
Dim oItem
For Each oItem In oDir.Files
WScript.Echo "looking at", oItem.Path
If dicFiNa.Exists(oItem.Name) Then
WScript.Echo "found", oItem.Name, "will copy"
End If
Next
For Each oItem In oDir.SubFolders
walk oItem, dicFiNa, vCargo
Next
End Sub
output:
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\6.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\5.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\4.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\3.txt
found 3.txt will copy *
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\2.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\1.txt
found 1.txt will copy *
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\deep\deeper\55.txt
found 55.txt will copy *
(*) as soon as the permission problem is solved.

Related

VBScript to copy/move file by lowest value in filename

I'm fairly new to scripting and am in need of some help. I have come across a unique situation for a Non-Profit client of ours that requires us to compare two or more files in a specific folder and move the file with the lowest numerical value in the filename.
This organization runs a non-profit radio station which has content submitted from hundreds of volunteers that name their files (when they record more than one) with various numbers at the end that either represent the date or the order in which the files are to be aired.
Essentially I am looking to create a vbscript (because I think it can be done this way) that will run with windows task scheduler 30 minutes prior to the first air date of the content and move the file with the lowest value (if more than one file exists) to a folder where it will be automatically processed by the radio automation software.
Examples of files in a folder might look something like these:
Folder1: (in this instance, "news.mp3" is the lowest value)
news.mp3
news1.mp3
news2.mp3
Folder2:
entertainment24.mp3
entertainment26.mp3
Folder3:
localnews081420.mp3
localnews081520.mp3
Honestly, on this one, I'm not even sure where to start. I've found several scripts that can look at file date or a specific numerical or date format in the filename, but none that can parse numbers from a filename and move/copy a file based on the numerical value. I'm hoping there is someone out there smarter than me that can point me in the right direction. Thanks for looking at my problem!
One script I've been playing with (from the scripting guy) looks at specific years in a filename:
strComputer = “.”
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colFiles = objWMIService.ExecQuery _
(“ASSOCIATORS OF {Win32_Directory.Name=’C:\Test’} Where ” _
& “ResultClass = CIM_DataFile”)
Set objRegEx = CreateObject(“VBScript.RegExp”)
For Each objFile in colFiles
objRegEx.Global = True
objRegEx.Pattern = “\d{4}”
strSearchString = objFile.FileName
Set colMatches = objRegEx.Execute(strSearchString)
strYear = colMatches(0).Value
strNewFile = “C:\Test\” & strYear & “\” & objFile.FileName & _
“.” & objFile.Extension
objFile.Copy(strNewFile)
objFile.Delete
Next
...but I can't seem to make the leap to regular numbers and then take a lowest value...
You can use FileSystemObject to Work with Drives, Folders and Files.
Also i used GETNUM function to get number.
Try my way :
sFolder = "C:\Test\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile in oFSO.GetFolder(sFolder).Files
Number=GETNUM(objFile.Name)
strNewFile = sFolder & Number & "\" & objFile.Name
If NOT (oFSO.FolderExists(sFolder & Number)) Then
oFSO.CreateFolder(sFolder & Number)
End If
oFSO.MoveFile objFile, strNewFile
Next
Function GETNUM(Str)
For i=1 To Len(Str)
if IsNumeric(Mid(Str,i,1)) Then
Num=Num&Mid(Str,i,1)
End if
Next
GETNUM=Num
End Function
For understanding the used code and how they work, open these sites and read all pages very carefully.
MoveFile method
Vbs Script to check if a folder exist

Reading and writing an INI file

I have been toying with the below script to be able to read settings for use with my HTA (creating a game launcher).
Here is my current HTA:
http://pastebin.com/skTgqs5X
It doesn't quite work, it complains of the WScript object being required. While I understand Echo will not work like that in a HTA I am having trouble modifying the code so it will work. Even just removing all Echo references it still has an issue with objOrgIni on line 200 of the below code (with the WScript references removed):
http://pastebin.com/pGjv4Gh1
I don't even need that level of error checking as the INI will exist etc, I just need a simple way to read from and write to an INI in my scripting. Any help you guys can give me in achieving that would be great, it's a little advanced for me just yet, but I'd love an explanation as to why it fails.
There is no easy way to use INI files with VBScript. You'd have to write the functionality yourself or find some existing code that does it.
But do you really need an INI specifically or just a way to save settings? You could just keep all of your settings in a Dictionary object and serialize it as needed.
For example, here are two functions -- LoadSettings and SaveSettings -- that do just that.
Public Function LoadSettings(strFile)
Set LoadSettings = CreateObject("Scripting.Dictionary")
Dim strLine, a
With CreateObject("Scripting.FileSystemObject")
If Not .FileExists(strFile) Then Exit Function
With .OpenTextFile(strFile)
Do Until .AtEndOfStream
strLine = Trim(.ReadLine())
If InStr(strLine, "=") > 0 Then
a = Split(strLine, "=")
LoadSettings.Add a(0), a(1)
End If
Loop
End With
End With
End Function
Sub SaveSettings(d, strFile)
With CreateObject("Scripting.FileSystemObject").CreateTextFile(strFile, True)
Dim k
For Each k In d
.WriteLine k & "=" & d(k)
Next
End With
End Sub
Imagine you had the following settings file saved at c:\settings.txt:
Count=2
Name=Obama
You'd use the functions above like this:
Const SETTINGS_FILE = "c:\settings.txt"
Dim Settings
Set Settings = LoadSettings(SETTINGS_FILE)
' Show all settings...
WScript.Echo Join(Settings.Keys, ", ") ' => Count, Name
' Query a setting...
WScript.Echo Settings("Count") ' => 2
' Update a setting...
Settings("Count") = Settings("Count") + 1
' Add a setting...
Settings("New") = 1
' Save settings...
SaveSettings Settings, SETTINGS_FILE

vbscript compare string contents (folder directory) of text files and creates the missing folders

I am currently working on a school assignment to compare strings within text files. These text files contains paths of folder directories. If a directory is not found on the other textfile, it will create that directory, else nothing will happen.
diretory1.txt contains directory strings that are:
C:\mcgfiles\avp
C:\mcgfiles\temp
C:\mcgfiles\logs\activity
C:\mcgfiles\logs\program
C:\mcgfiles\logs\status
C:\mcgfiles\generatedhtml
and diretory2.txt, contains the following
C:\mcgfiles
C:\mcgfiles\avp
C:\mcgfiles\temp
C:\mcgfiles\logs
C:\mcgfiles\logs\activity
C:\mcgfiles\logs\program
C:\mcgfiles\logs\status
C:\mcgfiles\generatedhtml
In the case of my textfiles, directories "C:\mcgfiles" and "C:\mcgfiles\logs" will be created on my drive C:\ since they are missing.
Here is the code I used:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Set objFile1 = objFSO.OpenTextFile("C:\scripts\directory1.txt", ForReading)
strAddresses = objFile1.ReadAll
objFile1.Close
Set objFile2 = objFSO.OpenTextFile("C:\scripts\directory2.txt", ForReading)
Do Until objFile2.AtEndOfStream
strCurrent = objFile2.ReadLine
If InStr(strAddresses, strCurrent) = 0 Then
objFSO.CreateFolder(strCurrent)
End If
Loop
It works fine when I use "C:\mcgfiles\temp" as the missing directory. But it cant differentiate what's missing when I use "C:\mcgfiles" or "C:\mcgfiles\logs". Maybe its because I used InStr function and it considers "C:\mcgfiles" and "C:\mcgfiles\logs" not missing since it can also be found in "C:\mcgfiles\logs\activity" etc.
I tried to use strComp but still nothing happens. Please help. Thank you
InStr() "returns the position of the first occurrence of one string within another". So "C:\mcgfiles" is found in "C:\mcgfiles\logs". If all of the pathes in the string you search in are terminated by an EOL marker (eg.g vbCrLf) you can use target & EOL as the needle:
>> haystack = "c:\a\b;c:\a;"
>> eol = ";"
>> needle = "c:\a" & eol
>> WScript.Echo InStr(haystack, needle)
>>
8
Other techniques - e.g. using a dictionary of the pathes - are possible, but would need more work.

vbscript error path not found while using movefolder method

I am fairly new to vbscript, and attempting to write a script that will pick up month and year stamped folders (2012_04) and move them to a year stamped folder (2012). I am getting a Path not found error though when I attempt to move the folder, and I can't seem to find an answer anywhere as to why it is happening.
for i = 0 to UBound(yearArray)
Set folder = fso.GetFolder(InputP)
Set subFold = Folder.Subfolders
yearStamp = yearArray(i)
if not fso.FolderExists(ArchiveP & yearStamp) then
fso.createFolder(ArchiveP & yearStamp)
end if
ArchiveP = ArchiveP & yearStamp & "\"
for each dateFold in subFold
Set fo = fso.GetFolder(InputP & dateFold.Name)
folderName = InputP & dateFold.name & "\"
foldName = fo.name & "\"
if left(foldName,4) = yearStamp then
fso.MoveFolder folderName , ArchiveP & foldName
end if
next
ArchiveP = UnChangeP & PreArchP
Next
The error happens at fso.MoveFolder folderName , ArchiveP & foldName and I can't figure out what is happening.
The error you're getting is caused by misconstructed paths. What you're trying to do is something like this:
fso.MoveFolder "C:\input\2013_03", "D:\archive\2013\2013_03"
However, what you're acutally doing is this:
fso.MoveFolder "C:\input\2013_03\", "D:\archive\2013\2013_03\"
^ ^
A trailing backslash is only valid in the destination path, and only if the destination path is the parent folder to which you want to move the source folder, i.e. your statement should look either like this:
fso.MoveFolder "C:\input\2013_03", "D:\archive\2013\"
or like this:
fso.MoveFolder "C:\input\2013_03", "D:\archive\2013\2013_03"
Avoid building paths via string concatenation. The FileSystemObjects provides a method BuildPath that will handle path separators correctly.
Your code is rather convoluted, BTW. Instead of using indexed access to yearArray you could simply iterate over all elements with a For Each loop. Also, your iteration over the subfolders of InputP already provides you with Folder objects. fso.GetFolder(InputP & dateFold.Name) is the exact same object as dateFold. Plus, Folder objects come with a Move method, so you'd only need to handle the destination path.
I believe your code could be simplified to the following, which should do what you want:
For Each year In yearArray
dst = fso.BuildPath(ArchiveP, year)
If Not fso.FolderExists(dst) Then fso.CreateFolder dst
For Each dateFold In fso.GetFolder(InputP).SubFolders
If Left(dateFold.Name, 4) = year Then dateFold.Move dst & "\"
Next
Next
In terms of performance it might be a good idea to switch the two loops, though. Iterating over folders means you have to read from disk whereas yearArray is in memory, thus the former iteration is bound to be slower than the latter. By making the subfolder iteration the outer loop (and putting the destination folder creation in a separate loop) you eliminate this bottleneck, because that way you read each subfolder just once.
For Each year In yearArray
dst = fso.BuildPath(ArchiveP, year)
If Not fso.FolderExists(dst) Then fso.CreateFolder dst
Next
For Each dateFold In fso.GetFolder(InputP).SubFolders
For Each year In yearArray
dst = fso.BuildPath(ArchiveP, year)
If Left(dateFold.Name, 4) = year Then dateFold.Move dst & "\"
Next
Next

Renaming pdf files with a batch file

I need to either write a batch file or a vbscript that will rename files. I need to keep everything in the file name up to the second "." but delete what comes after the second dot.
This is a sample of what the file names look like:
nnnnnnnnnnnnnnnn.xxxxxxxx.dddddddddd.pdf
n= 16 numbers 0-9
x= date in this format ex:02232008
d= 10 numbers 0-9, this is the part of the file name that I want to delete.
I need the d's from the sample above to be deleted but keep the rest of the file name the same. I need to be able to run this batch file on a folder that contains about 3,000 pdf files. It can either be put right back into the same folder or outputted into a different folder.
FOR /F "USEBACKQ delims=. tokens=1-4" %%F IN (`DIR /B /A-D "C:\Path\To\PDFs\"`) DO (
REN "%%~fF.%%G.%%H.%%I" "%%F.%%G.%%I"
)
If you have files that vary in how many periods there are, just need to add a simple argument to count how many period delimiters exist then execute.
In VBScript, you can use something like
' the file paths. hardcoded, but you could alternatively collect these via command line parameters
Const IN_PATH = "path\to\directory"
Const OUT_PATH = "path\to\another\directory"
' check that the directories exist. you could create them instead, but here
' it just throws an error as that's easier
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
if not fso.FolderExists(IN_PATH) then
err.raise 1,, "Path '" & IN_PATH & "' not found"
end if
if not fso.FolderExists(OUT_PATH) then
err.raise 1,, "Path '" & OUT_PATH & "' not found"
end if
dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file
for each file in infolder.files
dim name: name = file.name
dim parts: parts = split(name, ".")
' we're expecting a file format of a.b.c.pdf
' so we should have 4 elements in the array (zero-indexed, highest bound is 3)
if UBound(parts) = 3 then
' rebuild the name with the 0th, 1st and 3rd elements
dim newname: newname = parts(0) & "." & parts(1) & "." & parts(3)
' use the move() method to effect the rename
file.move fso.buildpath(OUT_PATH, newname)
else
' log the fact that there's an erroneous file name
WScript.Echo "Unexpected file format: '" & name & "'"
end if
next 'file
You would run it in a batch file thus, redirecting output to a log file
cscript rename-script.vbs > logfile.txt
This assumes that you can simply rely on the period to delimit the parts of the file name rather than the specifics of the format of the delimited parts.
To rearrange the date, which I think is in the parts(1) array element, you can simply extract each bit of the string because it's in a specific format:
'date in format mmddyyyy
dim month_, day_, year_, date_
month_ = left(parts(1), 2)
day_ = mid(parts(1), 3, 2)
year_ = right(parts(1), 4)
date_ = year_ & month_ & day_ ' now yyyymmdd
so when rebuilding the filename, you can replace parts(1) with the new formatted date
dim newname: newname = parts(0) & "." & date_ & "." & parts(3)
Using StringSolver, a semi-automatic renaming tool, just rename the first file, check that the generalized renaming is ok, and then accept it on all other files.
> move 1234567890123456.02232008.1946738250.pdf 1234567890123456.02232008.pdf
Get the explanation:
> move --explain
the file name until the end of the second number + the extension
If you are satisfied, you can run the semi-automated tool using move --auto or the succint version:
> move
DISCLAIMER: I am a co-author of this free software made for academic purposes.

Resources