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

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...
epicazoAsked:
Who is Participating?
 
Daz_1234Connect With a Mentor Commented:
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
 
skinnyquiverCommented:
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
 
Randy DownsOWNERCommented:
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
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
epicazoAuthor Commented:
not familiar with POWERSCRIPT... how do I run, or what ext is the script filename?
0
 
epicazoAuthor Commented:
i installed powershell 2.0 on my xp machine.  What's next?
0
 
epicazoAuthor Commented:
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
 
epicazoAuthor Commented:
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
 
epicazoAuthor Commented:
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
 
Randy DownsOWNERCommented:
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
 
Bill PrewConnect With a Mentor Commented:
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
 
epicazoAuthor Commented:
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
 
Bill PrewCommented:
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
 
Daz_1234Commented:
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
 
epicazoAuthor Commented:
I ran as VBS and error on Line 1  "Object required:'[string: "c"\ercharts"]'
code 800A01A8
0
 
Bill PrewCommented:
Change

set strSourceFolder = "C:\ercharts"


to

strSourceFolder = "C:\ercharts"

~bp
0
 
epicazoAuthor Commented:
Daz,

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

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.