AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Code design (Move old drawing revisions)
Goto page 1, 2  Next
 
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> Ask for Help
View previous topic :: View next topic  
Author Message
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Sun Nov 04, 2007 3:42 pm    Post subject: Code design (Move old drawing revisions) Reply with quote

I'd like to create a script for use at my work which involves moving old drawing revisions to a sub folder called "Old revisions". The drawings files can be either .PDF, .DWG, .DWF filetypes. The drawings numbers are 6 digits and are numbered sequantially from 000001 to 999999. The drawing revisions are 01 to 99. Example of some valid drawing filenames are:
123456-01-pdf
100145-05.pdf
114779-00.dwg
144778-09.dwf

I would like to create a script which runs through all of the files in a given folder (optionally recursively), finds any old drawing revisions and places them in a sub folder called "Old revisions". Example run through of program:
1. Allow user to select top folder.
2. Give option of searching recursively.
3. Loop through folders.
4. Find files 123456-00.pdf, 123456-01.pdf and 123456-02.pdf in same folder.
5. Move 123456-00.pdf and 123456-01.pdf into subfolder called "Old revisions".
6. A GUI which lists the files and allows the user to decide what to do with the files might be good but is not necessary.
7. Log actions to file.

I can handle all of the "encompassing" code, such as displaying a select folder window, logging results to file, creating the sub folder and moving the files etc. but I need some advise as to how to design the "core code" which will loop through all of the files and folders and find the old drawing file revisions.

I've considered using standard windows file search, freeware duplicate file finders, excel and any combination to create something semi-automatic but haven't found any satisfactory solutions. Any advice?
Back to top
View user's profile Send private message Visit poster's website
somebody
Guest





PostPosted: Sun Nov 04, 2007 3:52 pm    Post subject: . Reply with quote

Loop, FilePattern
Back to top
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Sun Nov 04, 2007 3:56 pm    Post subject: Reply with quote

I know that much, but things start to get complicated when you need to use several nested file loops and I was wondering how to structure them.
Back to top
View user's profile Send private message Visit poster's website
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Mon Nov 05, 2007 3:58 am    Post subject: Reply with quote

Revised entry to show final code, I had to use Exe2Ahk and the messages are in Norwegian, but it works like a charm. I found it quity difficult to figure ou the right mix between file/folder loops, variable/parsing loops and making it all work recursively. It would be interesting to hear how this sort of thing can be accomplished with cleaner/faster code, but judging by the lack of replies to this post I suppose the chances of someone around here coming up with a better solution are slim! Wink

Code:
; <COMPILER: v1.0.47.4>
FileSelectFolder, TopFolder, My Computer, 2, Velg mappen der gamle revisjonsfiler skal flyttes fra.
if ErrorLevel = 1
   exitapp
MsgBox, 3, , Søk i undermapper?
IfMsgBox Yes
   Recurse = true
IfMsgBox No
   Recurse = false
IfMsgBox Cancel
   exitapp

OldVersionFolder = Old versions

SplitPath, A_ScriptName, , , , ScriptNameNoExt
sLogfile = %ScriptNameNoExt%log.txt
FileMoveCountTotal = 0


FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
FileAppend, Startet: %A_Now%`nMappe: %TopFolder%`nUndermapper: %recurse%`n, %sLogfile%
FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
if recurse = true
{
  RecursiveFolderList = %TopFolder%`n
  Loop, %TopFolder%\*, 2, 1
  {
   RecursiveFolderList = %RecursiveFolderList%%A_LoopFileLongPath%`n
  }
}
else
{
   RecursiveFolderList = %TopFolder%`n
}

Loop, parse, RecursiveFolderList, `n
{
 if A_LoopField =
  continue
 thisfolder = %A_LoopField%
FolderRawList :=
MultipleRevList :=
MoveFileList :=

Loop, %thisfolder%\??????-??.???, 0, 0
   FolderRawList = %FolderRawList%%A_LoopFileName%`n

Sort, FolderRawList

Loop, parse, FolderRawList, `n
{
 if A_LoopField =
  continue

 StringLeft, NewFilePattern, A_LoopField, 6
 mcounter = 0
 HighestRev = 0
 Loop, %thisfolder%\%NewFilePattern%-??.???, 0, 0
 {
   mcounter += 1
   if mcounter > 1
    {
    IfNotInString, MultipleRevList, %NewFilePattern%
    MultipleRevList = %MultipleRevList%%NewFilePattern%`n
    break
   }
 }
}
  Sort, MultipleRevList

Loop, parse, MultipleRevList, `n
{
 if A_LoopField =
  continue
 ThisRev = 0
 HighestRev = 0
 Loop, %thisfolder%\%A_LoopField%-??.???, 0, 0
 {
  StringMid, ThisRev, A_LoopFileName, 9, 2, L
  if ThisRev > %HighestRev%
   HighestRev = %ThisRev%
 }

  Loop, %thisfolder%\%A_LoopField%-??.???, 0, 0
 {
  StringMid, ThisRev, A_LoopFileName, 9, 2, L
  if ThisRev < %HighestRev%
  {
   IfNotInString, A_LoopFileLongPath, %OldVersionFolder%
   {
      MoveFileList = %MoveFileList%%A_LoopFileLongPath%`n
   }
  }
 }
}

FileMoveCountThisFolder = 0
Loop, parse, MoveFileList, `n
{
 if A_LoopField =
  continue
 FileMoveCountThisFolder += 1
 FileMoveCountTotal += 1
 FileAppend, Flytter denne fila %A_LoopField% hit %thisfolder%\%OldVersionFolder%`n, %sLogfile%
 FileCreateDir, %thisfolder%\%OldVersionFolder%
 FileMove, %A_LoopField%, %thisfolder%\%OldVersionFolder%, 1

}
}
if FileMoveCountTotal = 0
   FinalResultString = Fant ingen gamle revisjonsfiler.
if FileMoveCountTotal = 1
   FinalResultString = Flyttet %FileMoveCountTotal% gammel revisjonsfil.
if FileMoveCountTotal > 1
   FinalResultString = Flyttet %FileMoveCountTotal% gamle revisjonsfiler.

msgbox, %FinalResultString%
FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
FileAppend, %FinalResultString%`n, %sLogfile%
FileAppend, Avsluttet %A_Now%`n, %sLogfile%
FileAppend, ------------------------------------------------------------------------------------------`n`n, %sLogfile%
Back to top
View user's profile Send private message Visit poster's website
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Thu Nov 08, 2007 12:38 am    Post subject: Reply with quote

Can someone please explain to me why this code:
Code:
thisfolder = c:\subfolder
Loop, %thisfolder%\??????-??.???
   msgbox, %A_LoopFileName%


will msgbox filenames such as "layout-1.jpg" and "123456-1.jpg"? I was expecting the filepattern to match only files that had the format
"123456-89.123" whereas the two examples above are "123456-8.123". Makes me wonder what else could go wrong here....
Back to top
View user's profile Send private message Visit poster's website
engunneer



Joined: 30 Aug 2005
Posts: 6847
Location: Pacific Northwest, US

PostPosted: Thu Nov 08, 2007 12:44 am    Post subject: Reply with quote

? matches any char, not just numbers. if you are looking for only numbers, you will have to regexmatch each file to see if it is numbers.
_________________
Unless otherwise noted, all code is untested.
Common Answers: 1.(Loops, Viruses, etc.) 2. Search 3.RTFM
Back to top
View user's profile Send private message Visit poster's website
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Thu Nov 08, 2007 12:53 am    Post subject: Reply with quote

Right, it should match any char but only one char correct? That's actually my question, I thought that was the entire difference between "?" and "*". Whereas "*" will match any char and any number of chars, "?" will only match any single char??? It seems I'm going to have to add some additional validation in any case.
Back to top
View user's profile Send private message Visit poster's website
engunneer



Joined: 30 Aug 2005
Posts: 6847
Location: Pacific Northwest, US

PostPosted: Thu Nov 08, 2007 12:59 am    Post subject: Reply with quote

good point - I mis-read. Sorry
_________________
Unless otherwise noted, all code is untested.
Common Answers: 1.(Loops, Viruses, etc.) 2. Search 3.RTFM
Back to top
View user's profile Send private message Visit poster's website
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Thu Nov 08, 2007 1:05 am    Post subject: Reply with quote

Bug??
Back to top
View user's profile Send private message Visit poster's website
Chris
Site Admin


Joined: 02 Mar 2004
Posts: 10480

PostPosted: Fri Nov 16, 2007 8:47 pm    Post subject: Reply with quote

I seem to remember there's something about file-system wildcards not working properly on long filenames (anything longer than 8+3 characters). In any case, the AutoHotkey code internally passes the wildcard to the OS's FindFirstFile() and FindNextFile() functions. Since AutoHotkey doesn't do any processing of the wildcards, it seems unlikely that this is a bug in AutoHotkey itself.
Back to top
View user's profile Send private message Send e-mail
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Sat Nov 17, 2007 12:34 am    Post subject: Reply with quote

Well, I did a standard Windows File Search on Windows XP and found 82 files that match the ??????-??.??? file pattern. Then I ran this script:

Code:
thisfolder = s:
count :=
Loop, %thisfolder%\??????-??.???, 0, 1
{
   count++
   ;msgbox, %A_LoopFileName%
}
msgbox, Found %count% files.


which also found 82 files. Then I created two files named "layout-1.jpg" and "123456-1.jpg" and did the search again, windows file search still returned 82 files, whereas the autohotkey script returned 84. Perhaps there is something wrong with the file system, but the file search somehow takes that into account? I have no clue, but whatever the source of the problem, it stills seems like a bug to me and it might be worth a note in the documentation. Although, it was a fairly simple for me to fix the misbehaviour of my script, the consequences could have been more serious.

[Edit:]Also, could someone help me out with the regular expression? I've never used regex before, this is the best I've come up with so far:
Code:
FoundPos := RegExMatch("123456-89.abc", "i){6\d}-{2\d\}.{3[a-z]}")


[Editdit:]I think I finally managed to hark out something that works. Can someone confirm that the line of code below won't give me any more surprises??

Code:
   FoundPos := RegExMatch(A_LoopFileName, "^\d\d\d\d\d\d-\d\d.[a-zA-Z][a-zA-Z][a-zA-Z]$")
Back to top
View user's profile Send private message Visit poster's website
Lexikos



Joined: 17 Oct 2006
Posts: 2739
Location: Australia, Qld

PostPosted: Mon Nov 19, 2007 5:37 am    Post subject: Reply with quote

Since '.' represents any character (except new-line if the dot-all option "s)" is not specified), it must be escaped. Also, I'd recommend using quantifiers to compact the expression.
Code:
FoundPos := RegExMatch(A_LoopFileName, "^\d{5}-\d\d\.[a-zA-Z]{3}$")

If you didn't escape the dot, all of the following would match:
Code:
12345-67.abc
12345-678abc
12345-67!abc
;etc.
Back to top
View user's profile Send private message
Murple (almost logged in)
Guest





PostPosted: Tue Nov 20, 2007 2:47 pm    Post subject: Reply with quote

Perfect. I didn't know the dot was a special character so I didn't think it had to be escaped. From now I, I think I will stick to regular expressions, since they seem to be more reliable and they are definetly much more configurable than standard file patterns. Thanks a whole lot!
Back to top
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Sun Dec 02, 2007 9:40 pm    Post subject: Reply with quote

In case anyone is interested and assuming nobody finds any bugs, here is the final script. The message box texts and logfile are written in Norwegian, but that shouldn't matter. It can be run from the command line or prompt the user. Would be interesting to get some feedback!

Code:
;This script loops through all files in a given folder, optionally recurses through all subfolders, finds all files that match ??????-??.???.
;The first 6 digits of this file pattern represent the drawing number and the following 2 represent the revision number.
;If script finds several matches of the same drawing number, it finds the highest revision number, and moves all files with lower revision numbers to a subfolder.

#SingleInstance force
#NoTrayIcon


 ;Initiliaze variables
 OldVersionFolder = OldVersions ;Name of subfolder to create and move old revision files to.
 TopFolder := ""
 DuplicatesMoved = 0
 TotalDuplicatesMoved = 0
 RecursiveFolderList := ""
 MoveErrorsOccured = 0
 Recurse := ""
 CommandLineMode = 0
 SplitPath, A_ScriptName, , , , ScriptNameNoExt
 sLogfile = %ScriptNameNoExt%log.txt
 SetWorkingDir, %A_ScriptDir%
 
 
 ;Run subroutines
 Gosub, GetCommandLineArguments
 Gosub, HandleNoCommandLineArguments
 Gosub, StartLog
 Gosub, StartCleaning
 Gosub, FinishLog
 Gosub, FinishMessage
 exitapp
return


;Clean TopFolder, optionally recurse through sub folders.
StartCleaning:
 CleanThisFolder(TopFolder)
 if recurse
 {
  Loop, %TopFolder%\*, 2, 1 ;Only include folders. Recurse.
  {
   ;msgbox, %A_LoopFileLongPath%
   CleanThisFolder(A_LoopFileLongPath)
  }
 }
return


;Clean this folder.
CleanThisFolder(ThisFolder)
{
 global sLogfile
 global TotalDuplicatesMoved
 FileMatchList := PopulateFileMatchList(ThisFolder)
 DuplicatesMoved := MoveDuplicateMatches(ThisFolder, FileMatchList)
 if DuplicatesMoved > 0
  FileAppend, Flyttet %DuplicatesMoved% filer i %ThisFolder%`n, %sLogfile%
 TotalDuplicatesMoved := TotalDuplicatesMoved + DuplicatesMoved
 ;msgbox, TotalDuplicatesMoved:%TotalDuplicatesMoved%
}


;Move duplicate drawing files
MoveDuplicateMatches(ThisFolder, FileMatchList)
{
 DuplicatesMoved = 0
 Loop, parse, FileMatchList, `n
 {
  global OldVersionFolder 
  global sLogfile
  global MoveErrorsOccured
  if A_LoopField =  ; Ignore blank.
   continue
  if A_Index > 1
  {
   StringLeft, LoopFieldDrawingnumber, A_LoopField, 6
   StringLeft, PreviousLoopFieldDrawingnumber, PreviousLoopField, 6
   if PreviousLoopFieldDrawingnumber = %LoopFieldDrawingnumber%
   {
    ;msgbox, Found duplicates:`n%PreviousLoopField%`n%A_LoopField%
   IfNotInString, thisfolder, \%OldVersionFolder%
   {
    ;msgbox, Gonna move duplicates.
    FileCreateDir, %thisfolder%\%OldVersionFolder%
    OldFullPathName = %thisfolder%\%PreviousLoopField%
    NewFullPathName = %thisfolder%\%OldVersionFolder%\%PreviousLoopField%
    SuccessfullMove := MoveThisFile(OldFullPathName, NewFullPathName)
    if SuccessfullMove
    {
     DuplicatesMoved++
    }
    else
     {     
     MoveErrorsOccured = 1
     FileAppend, Feil! Klarte ikke å flytte denne fila "%OldFullPathName%" hit "%NewFullPathName%"`n, %sLogfile%
    }
   }
   }
  }
  PreviousLoopField = %A_LoopField% 
 }
 return DuplicatesMoved
}


;Move this file
MoveThisFile(OldFullPathName, NewFullPathName)
{
 ;msgbox, % "Move these files:`n" OldFullPathName "`n" NewFullPathName
 FileMove, %OldFullPathName%, %NewFullPathName%, 1
 if errorlevel = 0
  SuccessfullMove = 1
 else
  SuccessfullMove = 0
 return SuccessfullMove
}


;Create list of all drawing files in this folder. A valid drawing file is a file that is named like this "??????-??.???", e.g. 123456-89.123
PopulateFileMatchList(ThisFolder)
{
 Loop, %thisfolder%\*, 0, 0 ;Loop through all files in this folder
 {
  ;msgbox, %thisfolder%\%A_LoopFileName%
  StringLower, A_LoopFileNameLowercase, A_LoopFileName ;Not necessary at the moment, but might simplify implementing restrictions on file extensions.
  FoundPos := RegExMatch(A_LoopFileNameLowercase, "^\d{6}-\d{2}.[a-zA-Z]{3}$")
  if FoundPos > 0
  {   
   FileMatchList = %FileMatchList%%A_LoopFileName%`n
  }
 }
 Sort FileMatchList
 ;msgbox, %thisfolder%:`n%FileMatchList%
 return FileMatchList
}


;Check and parse command line arguments.
GetCommandLineArguments:
;Syntax ExecutableName.exe /TopFolder:"C:\Documents and Settings\Erik Hansen\Desktop\Drawings" /Recurse ;SEEMS NOT TO WORK WITH UNC PATHS?!?!
param := ""
paramword := ""
if 0 > 0
{      Loop, %0%
      {
         param := %A_Index%  ;Fetch contents of the variable whose name is contained in A_Index.
         ;MsgBox, Parameter number`n%A_Index%`nis`n%param%.
         paramword = TopFolder
         if param contains /TopFolder:
         {
            StringLen, pLen, paramword
            iStartChar := pLen + 3
            StringLen, iLen, param
            iCharCount := iLen - iStartChar + 1
            StringMid, TopFolder, param, %iStartChar%, %iCharCount%
         }
            
         if param contains /Recurse
         {
            Recurse = 1
         }
      }
}
if Recurse <> 1
   Recurse = 0
   if InStr(FileExist(TopFolder), "D") 
   {
      if recurse in 1,0
      {   
         ;msgbox, Command line values successfully retrieved.`nTopFolder is: "%TopFolder%"`nRecurse is: "%Recurse%"         
         CommandLineMode = 1
      }
   }
return


;If program is not being run from the command line, prompt user for data.
HandleNoCommandLineArguments:
 if CommandLineMode <> 1 ;If no command line arguments are found, assume that script is not being run in command line mode.
 {
   FileSelectFolder, TopFolder, My Computer, 2, Velg mappen du vil sjekke for gamle revisjonsfiler. (Gamle revisjonsfiler vil bli flyttet til en undermappe.)
      if ErrorLevel = 1
         exitapp
   MsgBox, 3, , Søk i undermapper?
      IfMsgBox Yes
         recurse = 1
      IfMsgBox No
         recurse = 0
      IfMsgBox Cancel
         exitapp
 }
return


;Start logging
StartLog:
 FormatTime, iNowTime, , yyyy-MM-dd HH:mm:ss
 FileAppend, `n------------------------------------------------------------------------------------------`n, %sLogfile%
 FileAppend, Startet:                  %iNowTime%`nØverste mappe:            %TopFolder%`nSøk i undermapper:        %recurse%`nKjøres fra kommandolinje: %CommandLineMode%`n, %sLogfile%
 FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
return


;Finish logging
FinishLog:
 FinalResultString = Flyttet %TotalDuplicatesMoved% gamle revisjonsfiler.
 FormatTime, iNowTime, , yyyy-MM-dd HH:mm:ss
 FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
 FileAppend, Resultat:                 %FinalResultString%`nAvsluttet:                %iNowTime%`n, %sLogfile%
 FileAppend, ------------------------------------------------------------------------------------------`n`n, %sLogfile%
return


;Display FinalResultString
FinishMessage:
  if CommandLineMode <> 1 ;Do not display message if in commandline mode.
  {
   if MoveErrorsOccured
   {
   MsgBox, 52, Feilmelding, %FinalResultString%`nEnkelte filer kunne ikke flyttes, se logfilen for detaljer.`nØnsker du å åpne logfilen nå?
      IfMsgBox Yes
       run, %A_ScriptDir%\%sLogfile%
   }
   else
   {
    msgbox, %FinalResultString%
   }
  }
return


[Edit: Just realised this is missing probably the single most important "if block". Will update post when code has been updated and tested.]
Back to top
View user's profile Send private message Visit poster's website
Murp|e



Joined: 12 Jan 2007
Posts: 261
Location: Norway

PostPosted: Tue Dec 18, 2007 6:19 pm    Post subject: Debugging problems: Functions cannot contain functions. Reply with quote

Quote:
Error at line 127.

Line Text: PopulateAllDrawingsMatchList(ThisFolder)
Error: Functions cannot contain functions.

The program will exit.


I'm getting the above error and I can't seem to debug it. I've run through the entire script looking for missing/duplicate braces {}, and missing/duplicate function definitions, but I can't find anything. Any advice on how to debug??

This is my code:
Code:
;This script loops through all files in a given folder, optionally recurses through all subfolders, finds all files that match ??????-??.???.
;The first 6 digits of this file pattern represent the drawing number and the following 2 represent the draawing's revision number.
;If the script finds several matches on the same drawing number, it finds the highest revision number and moves all files with lower revision numbers to a subfolder called OldVersionsFolder.

 ;Set script environment
 #SingleInstance ignore
 #NoTrayIcon
 SetWorkingDir, %A_ScriptDir%

 
 ;Main
 Gosub, SetGlobalVars
 Gosub, GetIniVars
 Gosub, GetCommandLineArguments
 Gosub, HandleNoCommandLineArguments
 Gosub, StartLog
 Gosub, ProcessFolders
 Gosub, FinishLog
 Gosub, FinishMessage
 exitapp
return


;Set global variables
SetGlobalVars:
 TopFolder := ""
 Recurse := ""
 DuplicatesMoved := 0
 TotalDuplicatesMoved := 0
 MoveErrorsOccured = 0
 CommandLineMode := 0

 SplitPath, A_ScriptName, , , , ScriptNameNoExt
 sLogfile = %ScriptNameNoExt%log.txt
 sInifile = %ScriptNameNoExt%.ini
return


;Get variables from ini file
GetIniVars:
 IniRead, OldVersionFolder, sInifile, Main, OldVersionFolder, oldVersions
 IniRead, folderFilterOut, sInifile, Main, folderFilterOut, Transmittal
 folderFilterOut = %OldVersionFolder%,%folderFilterOut%
 IniRead, extFilterIn, sInifile, Main, extFilterIn, dwg`,dwf`,dxf`,pdf
return


;Process TopFolder and recurse through all subfolders if recurse is on.
ProcessFolders:
 DuplicatesMoved := ProcessThisFolder(TopFolder)
 TotalDuplicatesMoved := TotalDuplicatesMoved + DuplicatesMoved
 
 if recurse
 {
  Loop, %TopFolder%\*, 2, 1 ;Only include folders. Recurse.
  {
   ThisFolder = %A_LoopFileLongPath%
   validFolder := validateFolder(ThisFolder)
   if validFolder
   {
   DuplicatesMoved := ProcessThisFolder(A_LoopFileLongPath)
   TotalDuplicatesMoved := TotalDuplicatesMoved + DuplicatesMoved
   }
  }
 }
return


;Filter out bad folders
validateFolder(ThisFolder)
{
 global folderFilterOut
 if ThisFolder contains %folderFilterOut%
 {   
   validFolder = 0
 }
 else
 {
   validFolder = 1
 }
 ;msgbox, Validity of %ThisFolder% is %validFolder%.
 return validFolder
}


;Clean this folder.
ProcessThisFolder(ThisFolder)
{
 global sLogfile
 global TotalDuplicatesMoved
 AllDrawingsMatchList := PopulateAllDrawingsMatchList(ThisFolder)
 
 DuplicatesMoved := 0
 Loop, parse, AllDrawingsMatchList, `n
 {
  if A_LoopField =  ; Ignore blank.
   continue
 
  IfInString, SkipList, %A_LoopField%
   continue
 
  StringLeft, LoopFieldDrawingnumber, A_LoopField, 6
  StringMid, LoopFieldRevisionnumber, A_LoopField, 8, 2
  Transform, LoopFieldRevisionnumber, Floor, %LoopFieldRevisionnumber%
   
  ThisDrawingMatchList := PopulateThisDrawingMatchList(LoopFieldDrawingnumber, AllDrawingsMatchList)
  MatchCount := CountMatches(ThisDrawingMatchList)
 
  if MatchCount > 1
  {
   HighestRevThisDrawing := GetHighestRevThisDrawingMatchList(ThisDrawingMatchList)
   SkipList = %SkipList%%ThisDrawingMatchList%`n
   LowRevThisDrawingMatchList := PopulateLowRevThisDrawingMatchList(ThisDrawingMatchList, HighestRevThisDrawing)
   DuplicatesMoved := MoveAllFiles(ThisFolder, LowRevThisDrawingMatchList)
  }
 
  if DuplicatesMoved > 0
   FileAppend, Flyttet %DuplicatesMoved% filer i %ThisFolder%`n, %sLogfile%

  ;msgbox, TotalDuplicatesMoved:%TotalDuplicatesMoved%
  return TotalDuplicatesMoved
}


;Create list of all drawing files in this folder. A valid drawing file is a file that is named like this "??????-??.???", e.g. 123456-89.pdf
PopulateAllDrawingsMatchList(ThisFolder)
{
  global extFilterIn
  Loop, %thisfolder%\*, 0, 0 ;Loop through all files in this folder
  {
   ;msgbox, %thisfolder%\%A_LoopFileName%
   StringLower, A_LoopFileNameLowercase, A_LoopFileName ;Not necessary at the moment, but might simplify implementing restrictions on file extensions.
 
   ;Validate this file
   SplitPath, A_LoopFileNameLowercase, , , ThisFileExt, ,
   if ThisFileExt in %extFilterIn%
    validExt = 1
   else
    validExt = 0
   
   if validExt
   {
    FoundPos := RegExMatch(A_LoopFileNameLowercase, "^\d{6}-\d{2}.[a-zA-Z]{3}$")
    if FoundPos > 0
    {   
     AllDrawingsMatchList = %AllDrawingsMatchList%%A_LoopFileName%`n
    }
   }
  }
 Sort AllDrawingsMatchList
 ;msgbox, %thisfolder%:`n%AllDrawingsMatchList%
 return AllDrawingsMatchList
}


;Create list of drawings that match this drawing number.
PopulateThisDrawingMatchList(LoopFieldDrawingnumber, AllDrawingsMatchList)
{
 Loop, parse, AllDrawingsMatchList, `n
 {
  if A_LoopField =  ; Ignore blank.
   continue
  StringLower, A_LoopFieldLowerCase, A_LoopField ;Not necessary at the moment, but might simplify implementing restrictions on file extensions.
 
  IfInString, A_LoopFieldLowerCase, %LoopFieldDrawingnumber%
  {
   ThisDrawingMatchList = %ThisDrawingMatchList%%A_LoopFieldLowerCase%`n
  }
 }
 Sort ThisDrawingMatchList
 ;msgbox, %LoopFieldDrawingnumber%:`n%ThisDrawingMatchList%
 return ThisDrawingMatchList
}

;Count number of matches in list
CountMatches(ThisDrawingMatchList)
{
 Loop, parse, ThisDrawingMatchList, `n
 {
  if A_LoopField =  ; Ignore blank.
   continue
  MatchCount := A_Index
 }
 ;msgbox, MatchCount is %MatchCount%.
 return MatchCount
}


;Get highest revisions number for ThisDrawingMatchList
GetHighestRevThisDrawingMatchList(ThisDrawingMatchList)
{
 HighestRev := 0
 Loop, parse, ThisDrawingMatchList, `n
 {
  if A_LoopField =  ; Ignore blank.
   continue
  StringMid, LoopFieldRevisionnumber, A_LoopField, 8, 2
  Transform, LoopFieldRevisionnumber, Floor, %LoopFieldRevisionnumber%
  if LoopFieldRevisionnumber > %HighestRev%
   HighestRev := LoopFieldRevisionnumber
 }
 ;msgbox, %ThisDrawingMatchList%Highest rev: %HighestRev%
 return HighestRev
}


;Create list of all drawings that have revisions numbers lower than HighestRevThisDrawing
PopulateLowRevThisDrawingMatchList(ThisDrawingMatchList, HighestRevThisDrawing)
{
 Loop, parse, ThisDrawingMatchList, `n
 {
  if A_LoopField =  ; Ignore blank.
   continue
  StringMid, LoopFieldRevisionnumber, A_LoopField, 8, 2
  Transform, LoopFieldRevisionnumber, Floor, %LoopFieldRevisionnumber%
  if LoopFieldRevisionnumber < %HighestRevThisDrawing%
  {
   LowRevThisDrawingMatchList = %LowRevThisDrawingMatchList%%A_LoopField%`n
  }
 }
  ;msgbox, LowRevThisDrawingMatchList is`n%LowRevThisDrawingMatchList%
  return LowRevThisDrawingMatchList
}

;Move all files in LowRevThisDrawingMatchList
MoveAllFiles(ThisFolder, LowRevThisDrawingMatchList)
{
 global OldVersionFolder 
 global sLogfile
 global MoveErrorsOccured
 Loop, parse, LowRevThisDrawingMatchList, `n
 {
  if A_LoopField =  ; Ignore blank.
   continue
  FileCreateDir, %thisfolder%\%OldVersionFolder%
  OldFullPathName = %thisfolder%\%A_LoopField%
  NewFullPathName = %thisfolder%\%OldVersionFolder%\%A_LoopField%
  SuccessfullMove := MoveThisFile(OldFullPathName, NewFullPathName)
  if SuccessfullMove
  {
   DuplicatesMoved++
  }
  else
  {     
   MoveErrorsOccured = 1
   FileAppend, Feil! Klarte ikke å flytte denne fila "%OldFullPathName%" hit "%NewFullPathName%"`n, %sLogfile%
  }
 }
 ;msgbox, DuplicatesMoved is %DuplicatesMoved%.
 return DuplicatesMoved
}


;Move this file
MoveThisFile(OldFullPathName, NewFullPathName)
{
 ;msgbox, % "Move these files:`n" OldFullPathName "`n" NewFullPathName
 FileMove, %OldFullPathName%, %NewFullPathName%, 1
 if errorlevel = 0
  SuccessfullMove = 1
 else
  SuccessfullMove = 0
 ;msgbox, SuccessfullMove is %SuccessfullMove%
 return SuccessfullMove
}


;Check and parse command line arguments.
GetCommandLineArguments:
;Syntax ExecutableName.exe /TopFolder:"C:\Documents and Settings\New Folder\Desktop\Drawings" /Recurse ;SEEMS NOT TO WORK WITH UNC PATHS?!?!
param := ""
paramword := ""
if 0 > 0
{      Loop, %0%
      {
         param := %A_Index%  ;Fetch contents of the variable whose name is contained in A_Index.
         ;MsgBox, Parameter number`n%A_Index%`nis`n%param%.
         paramword = TopFolder
         if param contains /TopFolder:
         {
            StringLen, pLen, paramword
            iStartChar := pLen + 3
            StringLen, iLen, param
            iCharCount := iLen - iStartChar + 1
            StringMid, TopFolder, param, %iStartChar%, %iCharCount%
         }
            
         if param contains /Recurse
         {
            Recurse = 1
         }
      }
}
if Recurse <> 1
   Recurse = 0
   if InStr(FileExist(TopFolder), "D") 
   {
      if recurse in 1,0
      {   
         ;msgbox, Command line values successfully retrieved.`nTopFolder is: "%TopFolder%"`nRecurse is: "%Recurse%"         
         CommandLineMode = 1
      }
   }
return


;If program is not being run from the command line, prompt user for data.
HandleNoCommandLineArguments:
 if CommandLineMode <> 1 ;If no command line arguments are found, assume that script is not being run in command line mode.
 {
   FileSelectFolder, TopFolder, My Computer, 2, Velg mappen du vil renske for gamle revisjonsfiler`n(.DWG, .DWF, .DXF, .PDF).`nGamle revisjonsfiler blir flyttet til en undermappe som heter "OldVersions".
      if ErrorLevel = 1
         exitapp
   MsgBox, 3, , Søk i undermapper?
      IfMsgBox Yes
         recurse = 1
      IfMsgBox No
         recurse = 0
      IfMsgBox Cancel
         exitapp
 }
return


;Start logging
StartLog:
 FormatTime, iNowTime, , yyyy-MM-dd HH:mm:ss
 FileAppend, `n------------------------------------------------------------------------------------------`n, %sLogfile%
 FileAppend, Startet:                  %iNowTime%`nØverste mappe:            %TopFolder%`nSøk i undermapper:        %recurse%`nKjøres fra kommandolinje: %CommandLineMode%`n, %sLogfile%
 FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
return


;Finish logging
FinishLog:
 FinalResultString = Flyttet %TotalDuplicatesMoved% gamle revisjonsfiler.
 FormatTime, iNowTime, , yyyy-MM-dd HH:mm:ss
 FileAppend, ------------------------------------------------------------------------------------------`n, %sLogfile%
 FileAppend, Resultat:                 %FinalResultString%`nAvsluttet:                %iNowTime%`n, %sLogfile%
 FileAppend, ------------------------------------------------------------------------------------------`n`n, %sLogfile%
return


;Display FinalResultString
FinishMessage:
  if CommandLineMode <> 1 ;Do not display message if in commandline mode.
  {
   if MoveErrorsOccured
   {
   MsgBox, 52, Feilmelding, %FinalResultString%`nEnkelte filer kunne ikke flyttes, se logfilen for detaljer.`nØnsker du å åpne logfilen nå?
      IfMsgBox Yes
       run, %A_ScriptDir%\%sLogfile%
   }
   else
   {
    msgbox, %FinalResultString%
   }
  }
return


Last edited by Murp|e on Wed Dec 19, 2007 12:09 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> Ask for Help All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group