Move files older than x minutes - vbscript

I want the script to move all files (all file extensions *.*) older than 5 minutes from an INN folder to and ERROR folder. In my example C:\CopyFlow\Directory test\Inn\ to C:\CopyFlow\Directory test\Inn\Error
So I figured how to move files and how to find files older than x-time after looking it up. Howover, putting this together is the issue for me. Does anyone know how I can nail this?
This is what I got so far...
Dim age_threshold
age_threshold = 5
Dim folder_path
folder_path = WScript.Arguments(0)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.getFolder(folder_path)
Dim old_file_not_found
old_file_found = 0
For Each file in f.Files
Dim age
age = DateDiff("n", file.DateLastModified, Now)
If age > age_threshold Then
old_file_found = 1
.MoveFile "C:\CopyFlow\Directory test\Inn\*.*", "C:\CopyFlow\Directory test\Inn\Error"
Exit for
end if
Next
WScript.Quit
I'm used to batch, so this is a little bit greek to me (source http://www.evalesco.com/check-any-file-older-x-minutes-directory).
Now where do I set (dim?) my INN and ERROR folder in this script? And I'm pretty sure the if age followed by .movefile is wrong, so I probably need a little correction there.
Update Whats missing in the image is a backslash after error (\error\) in the move.file line.

You can't call methods without an object providing the method, so .MoveFile should be fso.MoveFile. However, in its current form the script would move all files from C:\CopyFlow\Directory test\Inn if any of the files in the folder passed as argument to the script is older than 5 minutes.
What you need to do is pass C:\test\inn as the argument to the script, and move only those files that actually are older:
If age > age_threshold Then
file.Move "C:\test\inn\error\"
End If

Related

VBScript does not oFS.FileExists a file in oFS.CreateFolder

I'm having a strange problem with VBScript. I'd like to implement some other code with a following test:
If there is a file named like [that] in the [folder], do not copy it into the [folder].
Thing is, I found a strange relation in oFS.FileExists, I'm able to use it in a manually created folder, as long as I manually copy and paste a file into it. Then oFS.FileExists works like a charm.
Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")
filestr = "C:\where\file\is\file.file"
If (oFS.FileExists(filestr)) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
But it's not exactly my point. I'd like to test if a file is already in the desired folder, and such folder will be generated automatically with oFS.CreateFolder. But when it comes to testing an automatically generated folder, it's a different story.
Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")
oFS.CreateFolder(destination & objFoldername)
Initially I thought it might be something wrong with the file I'm looking for. I moved it to some other place and the oFS.FileExists found it. So I figured it might be the case of the folder itself. I can see the folder is a Read Only folder. I tested it in other manually created Read Only folder, also found it.
Finally I manually created the folder exactly like oFS.CreateFolder would do it, pasted manually a file into it and... it also found a file just fine.
As I witnessed, every test I conduct in a generated folder is failed, but done in a manually created one, pass.
Remarkable!
Had anyone such a case? Do you know why oFS.FileExists puts a blind eye on something created itself?
I'm using 64-bit Windows 10 Home, and I wrote both scrips in Visual Studio Code if that would be relevant.
Cheers guys, I can't be the first one.
EDIT for leeharvey1
Thank you leeharvey1 that you took a minute to have a look at this. This is the code that creates the directories:
Dim oFS, oFile, objShell, objFolder, sFolderPathspec, destination, file
Set oFS = CreateObject("Scripting.FileSystemObject")
sFolderPathspec = "C:\folder\where\files\are\"
Set objShell = CreateObject ("Shell.Application")
destination = "C:\folder\where\new\folders\with\files\are\intended\to\be\"
Set objFolder = objShell.Namespace(sFolderPathspec)
For Each file In objFolder.Items
name = file.Name
wykonano = objFolder.GetDetailsOf(file, 12)
If wykonano = "" Then
wykonano = objFolder.GetDetailsOf(file, 3)
End If
arr = Split(wykonano, " ")
brr = Split(arr(0), "-")
rok = brr(0)
miesiac = brr(1)
objFoldername = rok & "-" & miesiac
If CStr(oFS.FolderExists(destination & objFoldername)) >< "Prawda" Then
oFS.CreateFolder(destination & objFoldername)
End If
newdestination = destination & objFoldername & "\" & name
oFS.CopyFile sFolderPathspec & name, newdestination, False
Next
The whole testing for file existence started because I could not have the following to run:
oFS.CopyFile sFolderPathspec & name, newdestination, False
I would love it to copy but not overwrite. False, is however syntax correct, opposing to "Fałsz" (which would be correct in my Windows language). But the code crashes as soon as it hits the file that is already in the destination folder. Maybe should I have some kind of code which will let the sequence of code continue over the crashes caused by already existing files? (Like Python has)
So it took me to the following problem of testing for existence.
I figured I'll use the following method of the Files collection. As mentioned above, I get fails every time I conduct a test in generated folder, but done in a manually created one, pass.
That's the code (so far in a different VBScript file):
filestr = "C:\where\file\is\file.file"
Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")
If oFS.FileExists(filestr) Then
MsgBox("Jest plik")
Else
MsgBox("Nie ma pliku")
End If
Function FileExists(FilePath)
Set oFS = CreateObject("Scripting.FileSystemObject")
If oFS.FileExists(FilePath) Then
FileExists=CBool(1)
Else
FileExists=CBool(0)
End If
End Function
If FileExists(filestr) Then
WScript.Echo "Does Exist"
Else
WScript.Echo "Does not exist"
End If
If (oFS.FileExists(filestr)) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
So, there are some details you wanted to know:
No, I am not working against a network shared file. It's all locally on my PC's ssd.
Have you tried disabling your anti-virus? No, if I'll need to do so in order to use it, I don't need the code.
I think I need to look for a file not for a folder, there is some kind of problem to locate the file. Do you think there could be also a problem to locate the folder itself?
Check folder Owner. Well, as far as I can see in Windows folder properties, it looks and have just the same settings as any other folder over there.
Thanks again leeharvey1 for your time!

Move first 10 files from a folder to another

I would like to know how I can move the first 10 files in folder to another folder? I have a folder which contains more than 50K files that need to be moved to another location for processing. I want to move 10 files at a time.
Please help to find a way using VBScript.
If you just need to move any 10 files from a folder, just maintain a file count as you iterate the Files collection of a Folder object.
For example:
intCount = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile In objFSO.GetFolder("c:\path\to\your\files").Files
objFile.Move "c:\new\path\"
intCount = intCount + 1
If intCount = 10 Then Exit For
Next
As I mentioned in the comments, there's no guarantee here which 10 files will get moved. Also of note, make sure to use a blackslash \ at the end of the path you're moving the file to (c:\new\path\) so that it's treated as a folder and not a new file name.

VBS: For-each loop (sometimes) iterates through file collection indefinitely

The goal of the following VBscript is to prepend a user-defined string to all files with a particular extension within a specified directory:
directory = "C:\Users\xxxxxxxx\Desktop\Test\" 'include final backslash
extension = ".doc" 'include period, ex: ".tab"
''''''''''''''''''''''''''''''''''''''''''
addStr = InputBox("Enter the text you would like to prepend:", , "xxxxxxxx_xxxxxxxxxx_x_xx_xxx_")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(directory)
Set colFiles = objFolder.Files
For Each file In colFiles
absPath = objFSO.GetAbsolutePathName(file)
currentExtension = objFSO.GetExtensionName(absPath)
If StrComp(currentExtension, Mid(extension, 2)) = 0 Then
file.Name = addStr & objFSO.GetFileName(file)
End If
Next
The script generally works well, but occasionally demonstrates this problematic behavior:
When running the script on a directory with lots of files and/or with files with long names, the script appears to iterate back over the collection of files (i.e. prepends to files that have already been prepended) and does so until the filenames become too long to be recognized by the FSO, crashing the script.
The threshold of the number of files/length of filenames at which this occurs appears to be very distinct and reproducible. For example, if I create a target directory (e.g. "...\Desktop\Test") with a file named '1.doc' that is copied/pasted several times, the script will properly rename up to 31 files, but it demonstrates the problematic behavior with 32+ files. Similarly, if I run the script twice over 31 files (generated in the same manner), the script demonstrates the problematic behavior on the second run.
Any thoughts as to the underlying issue are very much appreciated--thanks in advance!
You may have issues here because you're modifying files while iterating them. Try creating an array of file names first and then iterate over the array, changing the names.
ReDim a(colFiles.Count - 1)
i = 0
For Each File In colFiles
a(i) = File.Path
i = i + 1
Next
For i = 0 To UBound(a)
If StrComp(objFSO.GetExtensionName(a(i)), Mid(extension, 2)) = 0 Then
With objFSO.GetFile(a(i))
.Name = addStr & .Name
End With
End If
Next
The reason the above behaviour occurs is, because when you initially call Set colFiles = objFolder.Files, the first 32 files are retrieved, and placed into a cache. Once those 32 files are processed, then the system retrieves the first 32 filenames which have not been processed yet.
Since you have renamed the files after the initial call, the system sees those as new filenames that have not been processed yet. Since their names are still first alphabetically, they are placed into the 32-file cache, and processed again.
The solution by #Bond is the standard workaround for this issue. Due to limitations of vbs, this is the only practical resolution of this issue.

VBscript to delete subfolders

I am very new to vb script and i need a script to delete couple of thrid level subfolders based on starting name _SA and 2 days old
example
C:\abc\user1\temp\ _SA123
c:\abc\user2\temp_SA2345
c:\abc\user3\temp_SA4567
I want to delete the folder starting with _SA older than 2 days and I have 50+ users folder. please hlep
Thanks,
Chilli
Based upon the example data, this should work though I'd consider this the 4th level:
Edit: Because you asked nicely, I updated this to build a log in a variable that will list the path of the folder deleted, the date it was created, and the date you deleted it. This information shows up in a msgbox, but you could easily modify to print the data to a file instead.
Dim rootFolder
Dim fld
Dim subFld
Dim subsubFld
Dim Log
Set fso = CreateObject("Scripting.FileSystemObject")
Set rootFolder = fso.GetFolder("C:\abc\")
For Each fld In rootFolder.SubFolders
For Each subFld In fld.SubFolders
For Each subsubFld In subFld.SubFolders
If Len(subsubFld.Name) >= 3 Then
If Left(subsubFld.Name, 3) = "_SA" And subsubFld.DateCreated < Now() - 2 Then
Log = subsubFld.Path & ", Created " & subsubFld.DateCreated & ",Deleted" & Now & vbNewLine
subsubFld.Delete
End If
End If
Next
Next
Next
MsgBox Log
'Or you could print the log to a file.
It has no error trapping, (other than making sure the folder name is atleast 3 characters long) and will get permission denied if you don't have permission.
Note: the code I posted has indentations, it's just not display for some reason. If you want to see the indented code, hit the edit button.

Rename and Move Folders Using VB

I have the following script which works great if I need to rename files in a folder but now I want to move and rename folders from one mapped drive to another mapped drive. Can someone help me to modify the script to do so? I am failry new to VB so pardon if I can't firgure this out but it took me a little while to figure this one out and now I am not sure how to modify this script. Thank you in advance!
The folders by default are labeled A.1234, A.5678, and so on and will always have a different number assigned to them. I will keep the numbers in the label as they are PO numbers. So my end result desired is Ack~1234, Ack~5678, and so on.
Dim fso, f, f1, fc, s Set
fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("Y:\Test")
Set fc = f.Files
For Each f1 in fc
f1.move f1.ParentFolder & "\" & replace(f1.Name, "A.", "Ack~")
Again these folders exist on the root of a mapped drive and need to move to another mapped drive with the new names. If more info is needed please do not hesitate to ask.
UPDATE
I modified the script below to give an idea of what I'm looking to do.
Dim fso, objFol
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFol = fso.GetFolder("Z:\")
Set objFolders = objFol.Folders
For each folder in objFolders
fso.Movefolder folder, "Y:\" & Replace(fso.Name, "A.", "Ack~")
Next
This give me an error stating it does not support "Folder". There will be any number of folders in the Z drive and I need to move them all to the Y drive. Sorry if I didn't explain properly in the previous post.
The move command is taking a string, for which you're providing the parent folder of the file, so the file isn't moving. I think it'll be sufficient to provide a different folder location. For example:
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("Y:\Test")
Set fc = f.Files
For Each f1 in fc
f1.move "Z:\TargetFolder\" & replace(f1.Name, "A.", "Ack~")
Note: I've not tested this, but if there are problems then just ask
Additional Stuff after update:
The following code will allow you to move folders, and do the replacements you need to the folder name string.
Dim fso, objFol, objMoveFol, strPathBuild
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFol = fso.GetFolder("Y:\Test")
For Each objMoveFol In objFol.SubFolders
'Replace the root folder locations in the path
strPathBuild = Replace(objMoveFol, "Y:\Test", "Z:\TargetFolder\")
'Do the required other fiddle
strPathBuild = Replace(strPathBuild, "A.", "Ack~")
fso.Movefolder objMoveFol, strPathBuild
Next
Make sure you're really careful with this sort of thing, as getting is wrong can be fairly spectacular.

Resources