Link to home
Start Free TrialLog in
Avatar of Osley
Osley

asked on

Rename File to Folder Name then move the file to a different folder

Hi experts,

I need a batch or VB script to rename a file to its folder name, on completion, to then move the file to a different folder.

Example:
Folder/ folder name: One
File name in folder 'One': dkfjsdkf (disregard extension) - only the name is updated from 'dkfjsdkf' to 'One'

The folder path is C:\Test

On completion, the file renamed from 'dkfjsdkf' to 'One' is moved to: C:\Completed

I've been working on a script after digging around, however couldn't get it to work...
strStartFolder = "C:\Test"
Set objFSO = CreateObject("Scripting.FileSystemObject")

For Each objSubFolder In objFSO.GetFolder(strStartFolder).SubFolders
      RecurseFolders objSubFolder
Next

MsgBox "Done"

Sub RecurseFolders(objFolder)
      For Each objFile In objFolder.Files
            ' Go from the end of the base file name to the start to find how many numbers there are
            intNumberStart = 0
            For intPos = Len(objFSO.GetBaseName(objFile.Path)) To 1 Step -1
                  If IsNumeric(Mid(objFSO.GetBaseName(objFile.Path), intPos, 1)) Then intNumberStart = intPos
            Next
            If intNumberStart > 0 Then
                  objFile.Name = objFSO.GetFolder(objFSO.GetParentFolderName(objFile.Path)).Name & "" & Right("" & Mid(objFSO.GetBaseName(objFile.Path), intNumberStart), 3) & "." & objFSO.GetExtensionName(objFile.Path)
            Else
                  MsgBox objFile.Path & " does not have any number sequence."
            End If
      Next

      For Each objSubFolder In objFolder.SubFolders
            RecurseFolders objSubFolder
      Next
End Sub

Open in new window


Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of Steve Knight
Steve Knight
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Why not doing rename and move in one go? Lines 10 and 11 of Steve's script would then look like this:
    ECHO move /y "%%~d\%%~f" "%DestDir%"

Open in new window

and please remove line 12, there is no need to pause after each file found, we do not expect them to be that much.
The change above will also force the move, and overwrite an existing file in the destination folder. Steve's script will NOT overwrite anything, which might be intentional or not.
Avatar of Osley
Osley

ASKER

Hi Steve,

Thanks for this. It's only one level - as near as I can tell.

I ran the script and it's perfect. You're awesome. I can't tell you how long I've been fumbling around with this.

Thanks.
No problem. I wasn't sure if there was a need to do some process after the rename and before moving to completed which is why i split the two up but qlemo is right of course.

Steve