Link to home
Start Free TrialLog in
Avatar of epicazo
epicazoFlag for United States of America

asked on

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...
Avatar of skinnyquiver
skinnyquiver
Flag of United States of America image

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
Avatar of Randy Downs
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
Avatar of epicazo

ASKER

not familiar with POWERSCRIPT... how do I run, or what ext is the script filename?
Avatar of epicazo

ASKER

i installed powershell 2.0 on my xp machine.  What's next?
Avatar of epicazo

ASKER

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

Avatar of epicazo

ASKER

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

Avatar of epicazo

ASKER

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.

:(
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.
SOLUTION
Avatar of Bill Prew
Bill Prew

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
ASKER CERTIFIED SOLUTION
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
Avatar of epicazo

ASKER

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

Avatar of Bill Prew
Bill Prew

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
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.
Avatar of epicazo

ASKER

I ran as VBS and error on Line 1  "Object required:'[string: "c"\ercharts"]'
code 800A01A8
Change

set strSourceFolder = "C:\ercharts"


to

strSourceFolder = "C:\ercharts"

~bp
Avatar of epicazo

ASKER

Daz,

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