开发者

Why did this script go insane?

Aw man!

This is a VBScript that was supposed to change all the files in the directory that are 开发者_StackOverflow中文版named like

1229_002510 to 2010-12-29_002510

What ended up happening is the script never terminated.

After one pass through the file names, it KEPT GOING and prepended 2010- MULTIPLE TIMES until I killed the script.

The bug only appears if you launch the script through CScript at cmd.

(Launch with: cscript "filename.vbs")

So now I have a folderful of files like 2010-20-10-20-10-20-10-20-10-20-10-20-10-20-10-20-10-20-10-20-10-11-26_023335

Realize I'm a VBScript noob.

The script appears to work in test mode (just printing file names) but as soon as you have it work on actual files, it does exhibit the described behavior.

' shell script that changes dates like
' 1219_005530 to 2010-12-19_005530



' create a root filesystemobject:
Dim ofso
Set ofso = CreateObject( "Scripting.FileSystemObject" ) 

' create a folder object USING that root filesystem object
Dim folder

' that's the current directory
Set folder = ofso.GetFolder( "." )

' now, visit each file in the folder
Dim fileo
For Each fileo In folder.Files

  dim originalName
  originalName = CStr( fileo.Name )

  ' cut first 2 chars, prepend 2010-, re-add first 2 chars + "-"
  dim monthNumber
  monthNumber = Mid( originalName, 1, 2 )

  ' don't change the source file!
  If Right( originalName, 3 ) = "vbs" Then
    WSH.echo( "Not changing " & originalName )
  Else
    dim newName
    newName = "2010-" & monthNumber & "-" & Mid( originalName, 3 )

    WSH.echo( originalName )
    WSH.echo( newName & " < CHANGED TO" )


    ' ONLY ENABLE THIS LINE ONCE DEBUGGING COMPLETE  
    'fileo.Name = newName   
  End If

  Next

' PAUSE BEFORE EXIT  


I dont know what you dit, but i copy/pasted your script and it works just as you intended. (Windows 7)

Edit: Try to set a max on the times the script may go tru the loop. That will fix it. Might be that the script sees the renamed files as new files, thus creating an infinite loop.


You can perform this task in 2 steps. First scan a directory for files and collect their names into array, and then run through this array and rename files. This should be more reliable.

And consider to switch to JScript. VBS is just ugly compared to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜