randomly make directories with random names - vbs - vbscript

I have a folder with massive number of files, i need to make some folders and put them in to that folders (below 50 of each), Folder names can be any thing. I thought folder name to be numbers( 1,2,3.. etc )
here what i done, but doesn't work
Set fso=CreateObject("Scripting.FileSystemObject")
inputFldr =".\myFolder"
Set fldr=fso.getFolder(inputFldr)
dim i
i=0
fName = 0
for each file in fldr.files
i = i+1
If Not fso.FolderExists(fName) Then fso.CreateFolder(fName)
fso.MoveFile file, fName
if i>50 then
fName = fName + 1
i = 0
end if
next
wscript.echo done

Try this:
Dim i, fName, inputFldr, TmpFdr
Set fso = CreateObject("Scripting.FileSystemObject")
inputFldr = Replace(wscript.scriptfullname,wscript.scriptname,"myFolder")
Set fldr = fso.getFolder(inputFldr)
i = 0
fName = 0
wscript.echo "Input Folder: " & fldr.path
For Each file In fldr.Files
i = i + 1
TmpFdr = inputFldr & "\" & fName & "\"
if Not fso.FolderExists(TmpFdr) Then fso.CreateFolder (TmpFdr)
file.move TmpFdr
If i > 50 Then
fName = fName + 1
i = 0
End If
Next
set fldr=nothing
set fso=nothing

Related

Error Handling in VBScript to check for number of files in a folder

I have written a script to check that 4 files exist in a folder. I need to use the below error handling for this particular small piece of code.
This code checks various folders to see if it contains 4 files. If it does then good if it doesn't then its not good.
Code:
Const intOK = 0
Const intCritical = 2
Const intError = 3
Const ForReading=1,ForWriting=2,ForAppending=8
Dim filename,filenamemov,emailaddr
Dim arrFolders(17)
Dim argcountcommand,dteToday
Dim arg(4)
Dim strMailServer,Verbose,strExt,numfiles,intIndex
Dim intcount : intCount = 0
Dim stroutput
numfiles = 4 'how many minutes old are the files
Verbose = 0 '1 FOR DEBUG MODE, 0 FOR SILENT MODE
arrFolders(0) = "D:\AS2\Inbound\WESSEX"
arrFolders(1) = "D:\AS2\Inbound\EATWELL"
arrFolders(2) = "D:\AS2\Inbound\TURNER\"
For intIndex = 0 To UBound(arrFolders)
pt "Checking folder: " & arrFolders(intIndex)
If arrFolders(intIndex) = "" Then
pt "Empty folder value!"
Exit For
Else
Call checkfiles(arrFolders(intIndex))
End If
Next
If objFolder.Files.Count < 4 Then
WScript.Echo "CRITICAL - " & intCount & " File(s) over " & numfiles & "
minutes in " & stroutput
WScript.Quit(intCritical)
Else
WScript.Echo "OK - No directory contains less than 4 files"
WScript.Quit(intOK)
End If
Sub checkfiles(folderspec)
'check If any files exist on folder
On Error Resume Next
Dim objFso : Set objFso = CreateObject("Scripting.FileSystemObject")
'you can take this as input too using InputBox
'this will error If less than 4 files exist.
Dim objFolder : Set objFolder = objFso.GetFolder(strFolderPath)
If objfolder.Files.Count = 4 Then
MsgBox "This is Correct"
Else
MsgBox "This isnt Correct"
End If
Sub pt(txt)
If Verbose = 1 Then
WScript.Echo txt
End If
End Sub
If i understand your question, you want to
check a set of folders kept in an array for the number of files they contain
if any of the folders has less than 4 files, an error message should be displayed
the folder array CAN contain empty values and the routine should skip those
Apparently you have more plans considering all 'extra' variables you have in your code like Const ForReading=1,ForWriting=2,ForAppending=8 and Dim filename,filenamemov,emailaddr, but I left them out here, because they have nothing to do with the question at hand.
Option Explicit
Const intOK = 0
Const intCritical = 2
Const intError = 3
Dim Verbose, path, fileCount, minCount, intCount, errCount
Dim objFso, objFolder, intResult, strResult
Verbose = 0 '1 FOR DEBUG MODE, 0 FOR SILENT MODE
minCount = 4 'The minimal number of files each folder should have
Dim arrFolders(17)
arrFolders(0) = "D:\AS2\Inbound\WESSEX"
arrFolders(1) = "D:\AS2\Inbound\EATWELL"
arrFolders(2) = "D:\AS2\Inbound\TURNER\"
Set objFso = CreateObject("Scripting.FileSystemObject")
intResult = intOK 'assume all is well
strResult = "" 'to accumulate critical errors for each folder
intCount = 0 'the total running count of folders we have checked
errCount = 0 'the total count of errors (folders with less than 4 files) we have found
For Each path In arrFolders
If Len(path) > 0 Then
intCount = intCount + 1
WScript.Echo "Checking folder: " & path
Set objFolder = objFso.GetFolder(path)
fileCount = objfolder.Files.Count
'considering the "OK - No directory contains less than 4 files" message
'in your original post, this test needs to do a 'Greater Than Or Equal To', so use >=
If fileCount >= minCount Then
WScript.Echo "This is correct: " & path
Else
WScript.Echo "This is NOT correct: " & path
strResult = strResult & vbNewLine & "CRITICAL - " & fileCount & " File(s) in folder " & path
intResult = intCritical
errCount = errCount + 1
End If
End if
Next
'clean up used objects
Set objFolder = Nothing
Set objFso = Nothing
If errCount > 0 Then
'we have folders with errors
WScript.Echo strResult
Else
'This message implies that a folder is also 'Good' when more than 4 files exist
WScript.Echo "OK - All " & intCount & " directories contain at least " & minCount & " files"
End If
WScript.Quit(intResult)

read folder path and using the path to access the files and rename it

I want to write a VBScript that can access a config file which has the folder path. Once directed to the folder, there are documents with _DDMMYYYY. I want to remove the _ and the date stamp.
Can somebody help me please?
Option Explicit
Dim FSO: Set FSO = CreateObject("Scripting.FileSystemObject")
'Declare the variables to be used from the property file
Dim Folder
Dim objWMIService, objProcess, colProcess, obNetwork
Dim strComputer, WshShell, strComputerName
strComputer = "."
Set obNetwork = WScript.CreateObject("Wscript.Network")
strComputerName = obNetwork.ComputerName
Set obNetwork = Nothing
SetConfigFromFile("C:\Users\Lenovo\Desktop\RenameFile\ConfigPad.txt")
MsgBox "Folder = " & Folder
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run Folder
'---------- Get Variables from ConfigPad.txt ----------
Sub SetConfigFromFile(fileName)
Dim strConfigLine
Dim fConFile
Dim EqualSignPosition
Dim strLen
Dim VariableName
Dim VariableValue
Set fConFile = fso.OpenTextFile(fileName)
While Not fConFile.AtEndOfStream
strConfigLine = fConFile.ReadLine
strConfigLine = Trim(strConfigLine)
'MsgBox(strConfigLine)
If (InStr(1,strConfigLine,"#",1) <> 1 And Len(strConfigLine) <> 0) Then
EqualSignPosition = InStr(1, strConfigLine, "=", 1)
strLen = Len(strConfigLine)
VariableName = LCase(Trim(MID(strConfigLine, 1, EqualSignPosition-1))) 'line 34
VariableValue = Trim(Mid(strConfigLine, EqualSignPosition + 1, strLen - EqualSignPosition))
Select Case VariableName
'ADD EACH OCCURRENCE OF THE CONFIGURATION FILE VARIABLES(KEYS)
Case LCase("Folder")
If VariableValue <> "" Then Folder = VariableValue
End Select
End If
Wend
fConFile.Close
End Sub
'---------- Rename the documents ----------
Dim FLD
Dim fil
Dim strOldName
Dim strNewName
Dim strFileParts
'Set the folder you want to search.
Set FLD = FSO.GetFolder("C:\Users\Lenovo\Desktop\RenameFile\RenameFile.vbs")
'Loop through each file in the folder
For Each fil in FLD.Files
'Get complete file name with path
strOldName = fil.Path
'Check the file has an underscore in the name
If InStr(strOldName, "_") > 0 Then
'Split the file on the underscore so we can get everything before it
strFileParts = Split(strOldName, "_")
'Build the new file name with everything before the
'first under score plus the extension
strNewName = strFileParts(0) & ".txt"
'Use the MoveFile method to rename the file
FSO.MoveFile strOldName, strNewName
End If
Next
'Cleanup the objects
Set FLD = Nothing
Set FSO = Nothing
My config file only has this:
Folder = "C:\Users\Lenovo\Desktop\RenameFile\Test - Copy"
Set fso = CreateObject("Scripting.FileSystemObject")
Set TS = fso.OpenTextFile("C:\Users\Lenovo\Desktop\RenameFile\ConfigPad.txt")
SrcFolder = TS.ReadLine
Set fldr = fso.GetFolder(SrcFolder)
Set Fls = fldr.files
For Each thing in Fls
If Left(thing.name, 1) = "_" AND IsNumeric(Mid(thing.name, 2, 8)) Then
thing.name = mid(thing.name, 10)
End If
Next
This assumes the first line in the config file is a path. It renames any files starting with an underscore and followed by 8 digits.
Please Try This
configfile = "Config File Name Here" 'Example : C:\Documents\Config.txt
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set tf = objFSO.OpenTextFile(configfile, 1)
Do Until tf.AtEndOfStream
cl = tf.ReadLine
If InStr(cl, "Folder = ") > 0 Then
Folder = Replace(Replace(cl,"Folder = ",""),chr(34),"")
tf.Close
Exit Do
End If
Loop
For Each File in objFSO.GetFolder(Folder).Files
If InStr(File.Name, "_") > 0 And IsNumeric(Mid(File.Name,InStr(File.Name, "_") + 1,8)) Then
NewName = Replace(File.Name,Mid(File.Name,InStr(File.Name, "_"),9),"")
objFSO.MoveFile File.Path, objFSO.GetParentFolderName(File.Path) & "\" & NewName
End If
Next
MsgBox "Task Complete", vbOKOnly, "Remove Time Stamp"

Need to move a variable folder based on date

This is what I have.
stSourceFolder = "C:\Users\HIRENS\Admin\" & Replace(CStr(Date()), "/", ".")
stTargetFolder = "C:\Users\HIRENS\Admin\HIRENS\Admin\backup\" & _
Replace(CStr(), "DDMMYY")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
' The script will error out if it tries to create a directory that already exist
' so it is better to check for it first and only attempt to create it if it does
' not exist.
If Not fso.FolderExists(strDirectory) Then
' If it gets here then the folder for the current date does not yet exist and
' therefore is created.
Set objFolder = fso.CreateFolder(stTargetFolder)
End If
' This copies the files and overwrites them if they exist.
fso.CopyFolder stSourceFolder, destinationDir, OverwriteExisting
' If you entend to automate this script you should remove or rem out this next
' line.
WScript.Echo "Done"
'If the target-folder does not exist then it will be created.
objFSO.CopyFolder stSourceFolder, stTargetFolder
MsgBox "Folder copied"
Set fsoObj = Nothing
`On Error Resume Next
Dim sb : Set sb = CreateObject("System.Text.StringBuilder")
sb.AppendFormat "{0:ddMMyy}", Now() -1
'-----------------------------------------------------
TargetFolder = "C:\Users\"& sb.ToString &""
Set x = CreateObject("Scripting.FileSystemObject")
x.MoveFolder ""& TargetFolder &"" , "C:\Users\backup\"
'^^^ To move Variable folder DDMMYY
'------------------------------------------------------------
Dim fso, count, src, folder, file
Set fso = CreateObject("Scripting.FileSystemObject")
src = "C:\Users\backup\"& sb.ToString &"\"
stringtofind = "txt"
Set folder = fso.GetFolder(src)
count = 0
For Each file In folder.files
If instr(LCase(file.name), LCase(stringtofind)) > 0 Then
count = count + 1
End If
Next
WScript.Echo "PXE Files Count: " & count`

VBScript. Move a file and rename it with increment if exists

I'm trying to create a vbscript that moves files from one directory to another, that increments the filename if the file allready exists. I.e. if file.ext exists, new filename is file_01.ext. If file_01.ext exists, new filename is file_02.ext, and so on. I can't get it to work. Any help would be very much appreciated.
Const cVBS = "Vaskedama.vbs" '= script name
Const cLOG = "Vaskedama.log" '= log filename
Const cFOL = "C:\fra\" '= source folder
Const cMOV = "C:\til\" '= dest. folder
Const cDAZ = -1 '= # days
Dim strMSG
strMSG = " files moved from " & cFOL & " to " & cMOV
MsgBox Move_Files(cFOL) & strMSG,vbInformation,cVBS
Function Move_Files(folder)
Move_Files = 0
Dim strDAT
Dim intDAZ
Dim arrFIL()
ReDim arrFIL(0)
Dim intFIL
intFIL = 0
Dim strFIL
Dim intLEN
intLEN = 0
Dim strLOG
strLOG = "echo " & cVBS & " -- " & Now & vbCrLf
Dim dtmNOW
dtmNOW = Now
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objGFO
Dim objGFI
If Not objFSO.FolderExists(cFOL) _
Or Not objFSO.FolderExists(cMOV) Then
MsgBox "A folder does not exist!",vbExclamation,cVBS
Exit Function
End If
Set objGFO = objFSO.GetFolder(folder)
Set objGFI = objGFO.Files
For Each strFIL In objGFI
strDAT = strFIL.DateCreated
intDAZ = DateDiff("d",strDAT,dtmNOW)
If intDAZ > cDAZ Then
intFIL = intFIL + 1
ReDim Preserve arrFIL(intFIL)
arrFIL(intFIL) = strFIL.Name
If intLEN < Len(strFIL.Name) Then
intLEN = Len(strFIL.Name)
End If
End If
Next
For intFIL = 1 To UBound(arrFIL)
strFIL = arrFIL(intFIL)
Do While (objFSO.FileExists(cMOV & strFIL))
strFil = CreateNewName(strFIL, intFIL)
Loop
objFSO.MoveFile folder & strFIL, cMOV & strFIL
strLOG = strLOG & "move " & folder & strFIL _
& Space(intLEN-Len(strFIL)+1) _
& cMOV & strFIL & vbCrLf
Next
Set objGFI = Nothing
Set objGFO = Nothing
strLOG = strLOG & "echo " & UBound(arrFIL) & " files moved"
objFSO.CreateTextFile(cLOG,True).Write(strLOG)
Set objFSO = Nothing
Move_Files = UBound(arrFIL)
End Function
Function CreateNewName(strValue, intValue)
CreateNewName = strValue & intValue
End Function
As I can't understand your script at all, I'll concentrate on the the task "build a new file name by incrementing a counter". Obviously you have to check for each file whether there is a file with the same name or this name + suffix in the destination folder. The answer to this question for file a is completely independent of all files in the source folder - so I doubt your array makes any sense.
In code:
Const cnMax = 3
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim oSrcDir : Set oSrcDir = goFS.GetFolder("..\testdata\FancyRename\from")
Dim sDstDir : sDstDir = "..\testdata\FancyRename\to"
Dim oFile, nInc, sNFSpec
For Each oFile In oSrcDir.Files
WScript.Echo "looking at", oFile.Name
nInc = 0
sNFSpec = getNewFSpec(oFile.Name, sDstDir, nInc)
Do While goFS.FileExists(sNFSpec) And nInc <= cnMax
sNFSpec = getNewFSpec(oFile.Name, sDstDir, nInc)
Loop
If nInc > cnMax Then
WScript.Echo "won't copy to", sNFSpec
Else
WScript.Echo "will copy to ", sNFSpec
oFile.Copy sNFSpec
End If
Next
Function getNewFSpec(ByVal sFName, sDstDir, ByRef nInc)
If 0 < nInc Then
Dim sSfx
sSfx = goFS.GetExtensionName(sFName)
If "" <> sSfx Then sSfx = "." & sSfx
sSfx = "_" & Right("00" & nInc, 2) & sSfx
sFName = goFS.GetBaseName(sFName) & sSfx
End If
nInc = nInc + 1
getNewFSpec = goFS.BuildPath(sDstDir, sFName)
End Function
some sample output:
looking at B.txt
will copy to ..\testdata\FancyRename\to\B.txt
looking at C.txt
will copy to ..\testdata\FancyRename\to\C.txt
looking at A.txt
will copy to ..\testdata\FancyRename\to\A.txt
looking at B.txt
will copy to ..\testdata\FancyRename\to\B_01.txt
looking at B.txt
won't copy to ..\testdata\FancyRename\to\B_03.txt

VBScript to Move files with particular extension

I currently have a VBscript that scans a folder for files and moves the files to particular folders depending on key words in the file name.
I need currently the script only scans the one level (ie. doesn't scan recursively) and I need to to search all sub folders too.
Can someone give me a hand with this?
EDIT: Since writing this script I have realized that I need to have this only move files with particular extensions from a particular folder and sub folders to other directories based on the file name.
For example I need only .mp4 and .avi files to be moved.
Can someone help me with this please? I have tried multiple things but still can't get the recursive scanning and moving or the extension specific moving working.
Below is my current script.
'========================================================
' Script to Move Downloaded TV Shows and Movies to
' correct folders based on wildcards in File Name
'========================================================
On Error Resume Next
Dim sTorrents, sTV, sMovie, sFile, oFSO
' create the filesystem object
Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")
' Create Log File
Set objLog = oFSO.OpenTextFile("c:\temp\log.txt", 8, True)
' Set Variables
sTorrents = "C:\Temp\torrents\"
sTV = "C:\Temp\TV Shows\"
sMovie = "C:\Temp\Movies\"
' Scan each file in the folder
For Each sFile In oFSO.GetFolder(sTorrents).Files
' check if the file name contains TV Show Parameters
If InStr(1, sFile.Name, "hdtv", 1) OR InStr(1, sFile.Name, "s0", 1) <> 0 Then
' TV Show Detected - Move File
objLog.WriteLine Now() & " - " & sFile.Name & " Detected as TV Show - Moving to " & sTV
oFSO.MoveFile sTorrents & sFile.Name, sTV & sFile.Name
' Move all other Files to Movies Directory
Else objLog.WriteLine Now() & " - " & sFile.Name & " Detected as Movie - Moving to " & sMovie
oFSO.MoveFile sTorrents & sFile.Name, sMovie & sFile.Name
End If
Next
If sTorrents.File.Count = 0 And sTorrents.SubFolders.Count = 0 Then
objLog.WriteLine Now() & " - There is nothing left to Process..."
objLog.Close
End If
Some notes:
Sub listfolders(startfolder)
Dim fs
Dim fl1
Dim fl2
Set fs = CreateObject("Scripting.FileSystemObject")
Set fl1 = fs.GetFolder(startfolder)
For Each fl2 In fl1.SubFolders
Debug.Print fl2.Path
''process the files
ProcessFiles fl2.Path
'Recursion: lists folders for each subfolder
listfolders fl2.Path
Next
End Sub
''Code copied from question
Sub ProcessFiles(sPath)
' Scan each file in the folder
For Each sFile In oFSO.GetFolder(sPath).Files
' check if the file name contains TV Show Parameters
If InStr(1, sFile.Name, "hdtv", 1) OR InStr(1, sFile.Name, "s0", 1) <> 0 Then
' TV Show Detected - Move File
objLog.WriteLine Now() & " - " _
& sFile.Name & " Detected as TV Show - Moving to " & sTV
oFSO.MoveFile sTorrents & sFile.Name, sTV & sFile.Name
' Move all other Files to Movies Directory
Else
objLog.WriteLine Now() & " - " _
& sFile.Name & " Detected as Movie - Moving to " & sMovie
oFSO.MoveFile sTorrents & sFile.Name, sMovie & sFile.Name
End If
Next
End Sub
before the extension put a * that will find all files with that externsion.
Example: oFSO.MoveFile (PATH\*.EXTERNSION)
here is a recusive function to list files in folders and sub folders
it's tested and working, but you'll probably need some adaptation to your own forkflow. And it's not the most optimized, but it's simple to read
Sub test()
aFiles = F_ListFilesInDirAndSubDir("C:\foo\folder")
'then, add some code to parse the array:
For i = 0 to UBound(aFiles)
'Move or not to move, that is what your code should tell
Next
End Sub
Public Function F_ListFilesInDirAndSubDir(ByVal sDir)
'===============================================================================
'Get the list of files in a directory and in all its sub directories With the full path
'===============================================================================
Dim sChild As String
Dim aFolders As Variant
Dim aFiles As Variant
Dim aChildFiles As Variant
Dim i As Long
Dim j As Long
F_ListFilesInDirAndSubDir = aFiles
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(sDir) Then Exit Function
'Get the files in the directory
aFiles = F_ListFilesInDir(sDir)
'Add the fullpath
For i = 0 To UBound(aFiles)
If aFiles(i) <> "" Then
aFiles(i) = sDir & "\" & CStr(aFiles(i))
End If
Next
'get the folders
aFolders = F_ListFoldersInDir(sDir)
'for each folders, push the files in the file list
For i = 0 To UBound(aFolders)
If aFolders(i) <> "" Then
sChild = sDir & "\" & CStr(aFolders(i))
'Recursive call on each folders
aChildFiles = F_ListFilesInDirAndSubDir(sChild)
'Push new items
For j = 0 To UBound(aChildFiles)
If aChildFiles(j) <> "" Then
ReDim Preserve aFiles(UBound(aFiles) + 1)
aFiles(UBound(aFiles)) = aChildFiles(j)
End If
Next
End If
Next
F_ListFilesInDirAndSubDir = aFiles
End Function
Public Function F_ListFilesInDir(ByVal sDir)
'===============================================================================
'Get the list of files in a directory
'===============================================================================
Dim aList As Variant
Dim i As Long
Dim iChild As Long
Dim oFile
Dim oFolder
Dim oChildren
ReDim aList(0)
F_ListFilesInDir = aList
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(sDir) Then Exit Function
Set oFolder = fs.GetFolder(sDir)
Set oChildren = oFolder.Files
iChild = CDbl(oChildren.Count) - 1
If iChild = -1 Then Exit Function
ReDim aList(iChild)
i = 0
For Each oFile In oChildren
aList(i) = oFile.Name
i = i + 1
Next
F_ListFilesInDir = aList
End Function
Public Function F_ListFoldersInDir(ByVal sDir As String) As Variant
'===============================================================================
'Get the list of folders in a directory
'===============================================================================
Dim aList As Variant
Dim i As Long
Dim oDir
Dim oFolder
Dim oChildren
ReDim aList(0)
F_ListFoldersInDir = aList
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(sDir) Then Exit Function
Set oFolder = fs.GetFolder(sDir)
Set oChildren = oFolder.SubFolders
If oChildren.Count = 0 Then Exit Function
ReDim aList(oChildren.Count - 1)
i = 0
For Each oDir In oChildren
aList(i) = oDir.Name
i = i + 1
Next
F_ListFoldersInDir = aList
End Function

Resources