Solved

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

Posted on 2011-09-07
16
814 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
ID: 36497151
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
ID: 36497158
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
ID: 36497409
not familiar with POWERSCRIPT... how do I run, or what ext is the script filename?
0
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 

Author Comment

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

Author Comment

by:epicazo
ID: 36497719
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
ID: 36497731
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
ID: 36497759
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
ID: 36498301
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
 
LVL 53

Assisted Solution

by:Bill Prew
Bill Prew earned 100 total points
ID: 36499150
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 13

Accepted Solution

by:
Daz_1234 earned 400 total points
ID: 36501481
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
ID: 36540130
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 53

Expert Comment

by:Bill Prew
ID: 36540151
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 13

Expert Comment

by:Daz_1234
ID: 36540157
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
ID: 36540266
I ran as VBS and error on Line 1  "Object required:'[string: "c"\ercharts"]'
code 800A01A8
0
 
LVL 53

Expert Comment

by:Bill Prew
ID: 36540276
Change

set strSourceFolder = "C:\ercharts"


to

strSourceFolder = "C:\ercharts"

~bp
0
 

Author Closing Comment

by:epicazo
ID: 36540848
Daz,

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

Featured Post

Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I don't know if many of you have made the great mistake of using the Cisco Thin Client model with the management software VXC. If you have then you are probably more then familiar with the incredibly clunky interface, the numerous work arounds, and …
I use more than 1 computer in my office for various reasons. Multiple keyboards and mice take up more than just extra space, they make working a little more complicated. Using one mouse and keyboard for all of my computers makes life easier. This co…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

831 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