Solved

bat or vbs Script to move files based on file name...

Posted on 2011-09-07
16
774 Views
Last Modified: 2012-05-12
Hello experts.

I am wondering if it's possible to get the first 8 characters of file and move the files to a folder name matching  8 char prefix.  I guess it would first check to see of folder exist, if not then create one.

Here is an example:
CONTENTS IN ROOT FOLDER (C:\ERCharts\MARINA):
20110830_5474796.PDF
20110830_5474796.TIFF
20110831-5212510.TIFF

--- When I run my script -----

The above files will be moved to the following

 C:\ERCharts\MARINA\20110830
 ---> 20110830_5474796.PDF
 ---> 20110830_5474796.TIFF
 C:\ERCharts\MARINA\20110831
 ---> 20110831-5212510.TIFF

Thanks for your expertise...
0
Comment
Question by:epicazo
  • 8
  • 3
  • 2
  • +2
16 Comments
 
LVL 3

Expert Comment

by:skinnyquiver
Comment Utility
I would advise powershell because of the regex matching.

you could modify this script to have it create the folders then move the files

$source = "C:\test"
$destination = "C:\test2"
$filter = [regex] "^[0-9]{6}\.(jpg|gif)"

$bin = Get-ChildItem -Path $source | Where-Object {$_.Name -match $filter}
foreach ($item in $bin) {Copy-Item -Path $item.FullName -Destination $destination}

I got this script from http://superuser.com/questions/149537/windows-file-copy-move-with-filename-regular-expressions
0
 
LVL 29

Expert Comment

by:Randy Downs
Comment Utility
You could also modify this one. Script is explained on the following link.
http://blogs.technet.com/b/heyscriptingguy/archive/2007/10/24/hey-scripting-guy-how-can-i-move-files-based-on-a-value-in-the-file-name.aspx

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
0
 

Author Comment

by:epicazo
Comment Utility
not familiar with POWERSCRIPT... how do I run, or what ext is the script filename?
0
 

Author Comment

by:epicazo
Comment Utility
i installed powershell 2.0 on my xp machine.  What's next?
0
 

Author Comment

by:epicazo
Comment Utility
Could anybody provide me full working syntax?   I am getting error messages:

Copy-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\ERCharts\MoveFiles.ps1:7 char:41
+ foreach ($item in $bin) {Copy-Item -Path <<<<  $item.FullName -Destination $destination}
    + CategoryInfo          : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CopyItemCommand
 

cls
$source = "C:\test" 
$destination = "C:\test\NEW" 
$filter = [regex] "^[0-9]{6}\.(PDF|TIFF)"

$bin = Get-ChildItem -path $source | Where-Object {$_.Name -match $filter} 
foreach ($item in $bin) {Copy-Item -Path $item.FullName -Destination $destination}

Open in new window

0
 

Author Comment

by:epicazo
Comment Utility
Here is the error message when I run the following script
Unexpected token '&' in expression or statement.
At C:\ERCharts\ArchiveImages.ps1:4 char:46
+ Set objWMIService = GetObject("winmgmts:\\" & <<<<  strComputer & "\root\cimv2")
    + CategoryInfo          : ParserError: (&:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

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\new\" & strYear & "\" & objFile.FileName & _
        "." & objFile.Extension
    objFile.Copy(strNewFile)
    objFile.Delete
Next

Open in new window

0
 

Author Comment

by:epicazo
Comment Utility
I guest, to clarify things... I want to be able to truncate the left 8 charactors of the file name and use that as the folder to move the matching files into it.   Hope I am making sense.

:(
0
 
LVL 29

Expert Comment

by:Randy Downs
Comment Utility
The article I linked is looking for 4 digit values. You may want to look for 8 digit values.

As to your error - Make sure your editor is not adding extra characters.

Maybe your error is similar to this
http://stackoverflow.com/questions/1522478/unexpected-token-with-msbuild-script
I suggest you to use a xml editor
------------------
 we’re only going to show you how to grab all the 4-digit values; it’s up to you to determine which of those values represents the year.

objRegEx.Pattern = "\d{4}"
 \d{4} is simply regular expression syntax for 4 consecutive digits.


we can perform this same task against a remote computer. All we have to do is assign the name of that computer to the variable strComputer, like so:

strComputer = "atl-fs-01"
After we make our connection to the WMI service, we use this crazy-looking line of code to retrieve a collection of all the files found in the folder C:\Test:

Set colFiles = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='C:\Test'} Where " _
        & "ResultClass = CIM_DataFile")
Like we said, it’s crazy looking, which is the nature of WMI’s Associators Of queries. However, all we’re doing is retrieving all the files (instances of the CIM_DataFile class) that can be found in (are associators of) the folder C:\Test (Win32_Directory.Name='C:\Test'). Once we have that collection in hand we next create an instance of the VBScript.RegExp object; at that point, we’re ready to do some serious file management.

What’s that? What’s the VBScript.RegExp object for? Well, that’s the object that enables us to do a regular expressions search on each file name. We don’t know, in advance, what year (or years) are going to appear in each file name; the year could be 1912, it could be 1987, it could be 2008. If we wanted to, we could create a seemingly-endless series of InStr commands that methodically look for each of these possibilities: 1913; 1914; 1915; 1916; 1917; etc. Alternatively, we could use a simple regular expression to search for any value consisting of 4 consecutive digits.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 51

Assisted Solution

by:Bill Prew
Bill Prew earned 100 total points
Comment Utility
Can be done fairly easily with a plain BAT batch script, as follows.

@echo off
set BaseDir=C:\ERCharts\MARINA
for /F "tokens=1,2 delims=_" %%A in ('dir /b /a-d "%BaseDir%\*.*"') do (
  if not exist "%BaseDir%\%%A" md "%BaseDir%\%%A"
  move "%%A_%%B" "%BaseDir%\%%A"
)

Open in new window

~bp
0
 
LVL 12

Accepted Solution

by:
Daz_1234 earned 400 total points
Comment Utility
I would go with Bill's straightforward batch example above,  but if you need VBScript and / or want to add in some elaborate error checking later then you can start with this very basic VBScript version:
strSourceFolder = "C:\Temp\Source"

If Right(strSourceFolder, 1) <> "\" Then strSourceFolder = strSourceFolder & "\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set objSource = fso.GetFolder(strSourceFolder)
For Each oFile In objSource.Files
    strFirst8 = Left(oFile.Name, 8)
    If Not fso.FolderExists(strSourceFolder & strFirst8) Then
        fso.CreateFolder strSourceFolder & strFirst8
    End If
    fso.MoveFile strSourceFolder & oFile.Name, strSourceFolder & strFirst8 & "\"
Next

Open in new window


Hope this helps,
Daz.
0
 

Author Comment

by:epicazo
Comment Utility
I get error "1) was unexpedcted..."


C:\SysAdmin>set strSourceFolder = "C:\ercharts"
1) was unexpected at this time.
C:\SysAdmin>If Right(strSourceFolder, 1) <> "\" Then strSourceFolder = strSource
Folder & "\"
C:\SysAdmin>

set strSourceFolder = "C:\ercharts"

If Right(strSourceFolder, 1) <> "\" Then strSourceFolder = strSourceFolder & "\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set objSource = fso.GetFolder(strSourceFolder)
For Each oFile In objSource.Files
    strFirst8 = Left(oFile.Name, 8)
    If Not fso.FolderExists(strSourceFolder & strFirst8) Then
        fso.CreateFolder strSourceFolder & strFirst8
    End If
    fso.MoveFile strSourceFolder & oFile.Name, strSourceFolder & strFirst8 & "\"
Next

Open in new window

0
 
LVL 51

Expert Comment

by:Bill Prew
Comment Utility
How did you execute the vbscript solution you are testing, you need to save it as a VBS file and either double click it from Explorer, or open a command prompt and do:

cscript yourfile.vbs

~bp
0
 
LVL 12

Expert Comment

by:Daz_1234
Comment Utility
It is a VBScript: it looks like you tried to run it as a batch file.

Save it with a .vbs  extension not bat or cmd and try again.

Daz.
0
 

Author Comment

by:epicazo
Comment Utility
I ran as VBS and error on Line 1  "Object required:'[string: "c"\ercharts"]'
code 800A01A8
0
 
LVL 51

Expert Comment

by:Bill Prew
Comment Utility
Change

set strSourceFolder = "C:\ercharts"


to

strSourceFolder = "C:\ercharts"

~bp
0
 

Author Closing Comment

by:epicazo
Comment Utility
Daz,

Your code worked very nice.  Bill your code sometimes worked, but didn't always move files -- not sure why.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Many people tend to confuse the function of a virus with the one of adware, this misunderstanding of the basic of what each software is and how it operates causes users and organizations to take the wrong security measures that would protect them ag…
Today, still in the boom of Apple, PC's and products, nearly 50% of the computer users use Windows as graphical operating systems. If you are among those users who love windows, but are grappling to keep the system's hard drive optimized, then you s…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now