I have a vbscript that is used to rename files. What I need to implement into the script is something that deletes the "new file" if it already exists.
For example: I have a batch of files that are named like this 11111111.dddddddd.pdf where the files get renamed to 11111111.pdf. The problem is that when I rename to the 11111111.pdf format I end of with files that are duplicated and then makes the script fail because you obviously cant have 2 files with the same name. I need it to rename the first one but then delete the others that are renamed the same.
Here is what I have so far for my IF statement but it doesnt work and I get and error that says "Type mismatch: 'FileExists". I am not sure how to get this part of the code to execute the way I would like. Any help or suggestions would be greatly appreciated.
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, ".")
dim acct_, date_
acct_ = parts(0)
date_ = parts(1)
' file format of a.c.pdf
if UBound(parts) = 2 then
' rebuild the name with the 0th and 2nd elements
dim newname: newname = acct_ & "." & parts(2)
' use the move() method to effect the rename
file.move fso.buildpath(OUT_PATH, newname)
if newname = FileExists(file.name) Then
newname.DeleteFile()
end if
end if
next 'file
You're close, you just need to delete the file before trying to over-write it.
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, ".")
if UBound(parts) = 2 then
' file name like a.c.pdf
dim newname: newname = parts(0) & "." & parts(2)
dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)
' warning:
' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
' only one of them will be saved as D:\OUT_PATH\ABC.PDF
if fso.FileExists(newpath) then
fso.DeleteFile newpath
end if
file.Move newpath
end if
next
fileExists() is a method of FileSystemObject, not a global scope function.
You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.
Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.
So you could use the block:
if NOT fso.FileExists(newname) Then
file.move fso.buildpath(OUT_PATH, newname)
else
fso.DeleteFile newname
file.move fso.buildpath(OUT_PATH, newname)
end if
Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.
IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat
Related
I have a folder which contains various tif files.I am using a simple move command which reads as
move "Source path/File name" "Destination path/"
I have tried a command which reads as:
move "Source path/File 1, File 2. File 3" "Destination Path/"
I am looking for a similar formula which can help me out. The reason why this code is important for me
In a scenario where iam moving only one file to destination folder
In another scenario, I have to choose 3 or more files to another destination folder. If I do this with generic formula it takes a longer time to accomplish.
Please do suggest on this.
move "Source path/File 1, File 2. File 3" "Destination Path/"
In a scenario where I am moving only one file to destination folder.
In another scenario, I have to choose 3 or more files to another destination folder.
Example:
Sample
If I do this with generic formula it takes a longer time to accomplish.
You might try the code below.
Sub MoveFiles()
Dim DestinationPath As String
Dim SourcePath As String
Dim FileNames As String
Dim Sp() As String
Dim i As Integer
SourcePath = Environ("USERPROFILE") & "\Desktop"
DestinationPath = "H:\TestFolder"
FileNames = "File1.txt,File2.txt,File3.txt"
If Right(SourcePath, 1) <> "\" Then SourcePath = SourcePath & "\"
If Right(DestinationPath, 1) <> "\" Then DestinationPath = DestinationPath & "\"
If Len(FileNames) Then
Sp = Split(FileNames, ",")
For i = 0 To UBound(Sp)
Sp(i) = Trim(Sp(i))
If Len(Dir(SourcePath & Sp(i))) Then
Name SourcePath & Sp(i) As DestinationPath & Sp(i)
End If
Next i
End If
End Sub
Set the Source and Destination paths according to your system. Enter as many or as few file names in one comma separated string. All named files will be moved if they exist at the SourcePath. If the destination path doesn't exist an error will occur.
I have a folder with 8 Excel files with the following naming convention:
date_All_Groups
date_HRFull_Status_All
date_RME_Groups_Excluded
These files are used for monthly reports, therefore the date will obviously always be different.
I will be using a macro to manipulate the data in each worksheet, however I cannot create the macro due the changing file name (the date) - the only guarantee I have is that each of these files will DEFINITELY contain a partial string match.
I have a script that finds the files in the location and will rename the file, but it only renames 1 file and its not the first file in the folder.
My issue is using the For Each loop effectively.
Here's the code I have:
Dim fso, folder, file
Dim folderName, searchFileName, renameFile1, renameFile2, renameFile3, renameFile4, renameFile5, renameFile6, renameFile7, renameFile8
'Path
folderName = "C:\test\"
'Future FileName
renameFile1 = "All Groups.csv"
renameFile2 = "Groups Excluded.csv"
renameFile3 = "No Exclusions.csv"
renameFile4 = "HR.csv"
renameFile5 = "AD Users.csv"
renameFile6 = "Encryption Status.csv"
renameFile7 = "ePO4 Not Encrypted.csv"
renameFile8 = "ePO5 Not Encrypted.csv"
' Create filesystem object and the folder object
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
' Loop over all files in the folder until the searchFileName is found
For Each file In folder.Files
' See If the file starts with the name we search
If InStr(file.Name, "All_Groups") then
file.Name = renameFile1
End If
If InStr(file.Name, "Groups_Excluded") Then
file.Name = renameFile2
End If
If InStr(file.Name, "No_Exclusions") Then
file.Name = renameFile3
End If
If InStr(file.Name, "HR") Then
file.Name = renameFile4
End If
If InStr(file.Name, "AD_Users") then
file.Name = renameFile5
End If
If InStr(file.Name, "Encryption_Status") then
file.Name = renameFile6
End If
If InStr(file.Name, "ePO4") then
file.Name = renameFile7
End If
If InStr(file.Name, "ePO5") then
file.Name = renameFile8
End If
Exit For
' echo the job is completed
WScript.Echo "Completed!"
Next
The original code I found was exactly as above, but with only one If statement inside the For Each loop and the Exit For was inside the If statement.
Currently when I execute the script, the code renames only one file and its always the HR file first.
If I execute the script again, it then starts with All Groups, then Groups Excluded, and so on.
And the "Echo Completed" does not do anything either.
If you just want to rename your files to "canonical" names you could do something like this, assuming that you just want the date from the beginning of the filename removed and the underscores replaced with spaces:
Set re = New RegExp
re.Pattern = "\d{4}-\d{2}-\d{2}_(.*\.csv)"
For Each f In folder.Files
For Each m In re.Execute(f.Name)
f.Name = Replace(m.Submatches(0), "_", " ")
Next
Next
If the files have the same "date" you only need Find for that, for excample (if the date is a iso date "YYYYMMDD") (Date Returns "today" date)
IsoDate=CStr(Year(Date)) & Right("0" & CStr(Month(Date)),2) & Right("0" & CStr(Day(Date)),2)
And the for each:
For Each file In folder.Files
If InStr(file.Name, IsoDate) = 1 then 'if is in the start of the string
file.Name = Mid(file.Name, Len(IsoDate)+1) 'The same name with out date
End IF
Next
I require a VBScript that finds the most recent file in a folder and renames it. I have been able to write the script so that it finds the most recent file. However, I cannot figure out how to correctly have the file renamed once identified. I have been able to rename the file with a basic name, confirming the script works.
The file name needs the letter "A" added in the middle.
The file will already be saved as 20160229_TITLES and it needs to become 20160229A_TITLES.
Below is a script I tried to just pull the year and add the "A". I figured if I could get the year to add to the beginning, I could then add in the month and year. The date will always be the current date. This continues to cause an error message.
Option Explicit
Dim fso, folder, file, Date, recentFile
Dim folderName, searchFileName, renameFileTo
folderName = "C:\Ticket\Test\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
Set recentFile = Nothing
For Each file In folder.Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf FormatDateTime(file.DateLastModified) = Date Then
Set recentFile = file
End If
Next
recentFile.Name = Replace(recentFile.Name, "_", "A_")
Assuming that the filename will always consist of a date followed by an underscore and some other text you could do several things:
replace underscores with "A_" (if there is only one underscore in the name):
file.Name = Replace(file.Name, "_", "A_")
split the name at the first underscore, append "A" to the first fragment and join the fragments back together:
arr = Split(file.Name, "_", 2)
arr(0) = arr(0) & "A"
file.Name = Join(arr, "_")
do a regular expression replacement:
Set re = New RegExp
re.Pattern = "^(\d{8})_"
file.Name = re.Replace(file.Name, "$1A_")
The answer #Ansgar provided helped me correctly rename the file, however, I learned that the script only searched for any file that was newer than any other file and renamed it. The following script correctly renames the file that was modified today. Thank you for all your help #Ansgar. :)
Option Explicit
Dim fso, folder, file, todaysDate, recentFile
Dim folderName, searchFileName, renameFileTo
folderName = "C:\Ticket\Test\"
todaysDate = Date()
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderName)
set recentFile = Nothing
For each file In folder.Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf DateValue (file.DateLastModified) = todaysDate then
Set recentFile = file
Exit For
End IF
Next
recentFile.Name = Replace(recentFile.Name, "_", "A_")
just looking for some help on this. I've tried a few different things and I'm stumped. I'm trying to take a check if a file exists in a directory, and if it does, then I want to rename add - Copy to the file name. Then it should check again if there is a conflict, and if there isn't it should move the file. Sounds simple enough, but it isn't working at all. Since I can't convert from String to DirectoryInfo, I have to declare multiple variables, and it just doesn't feel right. What can I do to fix this?
Dim fileExt As String = ""
Dim oldFileName As String = file.FullName
Dim newFileName As String = oldFileName
Dim newFileLocation = Environment.GetSpecialFolder(Environment.SpecialFolder.MyPictures) + "\" + file.Name
While FileIO.FileSystem.FileExists(newFileLocation) 'While File exists in new directory
'Add copy to filename
fileExt = fileType.Replace("*", "")
newFileName = newFileName.Remove(newFileName.LastIndexOf("."), (newFileName.Length - newFileName.LastIndexOf(".")))
newFileName += " - Copy"
newFileName += fileExt
'Rename file
FileSystem.Rename(oldFileName, newFileName)
'Declare a new DirInf variable because I can't use a string to set one
Dim newFile As New DirectoryInfo(newFileName)
'Move the new file to
newFile.MoveTo("C:\Users\" + Environ("USERNAME") + "\Pictures\")
ProgressBar.Value += 1
End While
You're looking for File.Move(), which takes two strings.
Also, "C:\Users\" + Environ("USERNAME") + "\Pictures\" is very wrong; many users do not have C: drives.
You should call Environment.GetSpecialFolder(Environment.SpecialFolder.MyPictures)
Basically, I need a script to move files to another folder that have been accessed and modified.
I'm new to scripting, so this may be a simple problem, but I'm stumped. Here's the error I'm getting:
Script: C:\Users\bmcwilliams\Desktop\pssitest.vbs
Line: 17
Char: 10
Error: File already exists
Code: 800A003A
Source: Microsoft VBScript runtime error
The destination folder is empty, so I'm not sure what's going on.
Below is the code I have. It's modified from the code listed in this post:
How to move files from a directory to another directory based on file size
' use a default source path
dim sourcepath: sourcepath = "C:\users\bmcwilliams\Desktop\TestUncompleted"
' use a default destination path
dim destinationpath: destinationpath = "C:\users\bmcwilliams\Desktop\TestCompleted"
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
dim sourcefolder: set sourcefolder = fso.GetFolder(sourcepath)
' loop through each file in the directory, compare size property against
' the limit and copy as appropriate
dim file, count: count = 0
for each file in sourcefolder.Files
dim createDate: createDate = file.DateCreated
dim modifyDate: modifyDate = file.DateLastModified
if createDate <> modifyDate Then
file.Move destinationpath
count = count + 1
end if
next
WScript.Echo("complete: " & count & " file(s) moved")
Any ideas? Any input is greatly appreciated. Thanks!
You are copying to the new location but do not supply the new name of the file. To fix the issue append a \ and the file name to the destination path.
file.Move destinationpath +"\" + file.name
If the destination path for moving a file is a folder and not the full path (including the destination filename), it must have a trailing backslash:
destinationpath = "C:\users\bmcwilliams\Desktop\TestCompleted\"
Otherwise the Move operation would detect that the destination (the folder) already exists and would thus fail.