Jump to content

Open all files within directory


Recommended Posts

Hello all,

I am new to this. I need a script that will open all the files within a directory and it's subdirectories that have the extension .dwg. Open 1 file run a script close the file and move to next until all the files within the subdirectories and directory has been processed. I think (probably wrong) the best step would to count all files the loop the open command until the count number is reached. Could anyone help me with this? Thanks.

Link to comment
Share on other sites

With the help of Blindwig's code which evilertoaster linked to above, this is what I hashed out,

You might never need many of the options in the functions depending on what you're trying to do.

But here goes:

CODE
$path = "C:\mydirectory"
$FileArray = _FileFindAllR($path, '*.dwg')
For $i = 1 To $FileArray[0]
    ShellExecute($FileArray[$i])
Next

;===============================================================================
;
; Function Name:    _FileFindAllR
; Description:      Returns a recursive list of files
; Parameter(s):     $Path = root path to begin the listing from
;                   $Mask = file mask to match
;                   $AttribFilter = File Attributes to filter files through.  See _FileFilterAttrib for details
;                   $ProgressTitle = A title to put on a progress window.  Empty String = no progress window
; Requirement(s):   $Path is an existing directory
; Return Value(s):  A 1-based array containing the full path of all found files
; Author(s):        Mike Ratzlaff <mike@ratzlaff.org>
; Revision:         20050622A
;
;===============================================================================
;
;Returns a recursive list of files under $Path, matching $Mask, and filtered through $AttribFilter
Func _FileFindAllR($Path, $Mask='*', $AttribFilter='dhs', $ProgressTitle = @ScriptName)
    Dim $i, $aDirList = _FileGetTreeList($Path, $ProgressTitle), $FileList[@extended + 1]
    If $ProgressTitle <> '' Then ProgressOn($ProgressTitle, 'Scanning files...', '', -1, -1, 16)
    For $i = 1 to $aDirList[0]
        If $ProgressTitle <> '' Then ProgressSet($i * 100 / $aDirList[0], $aDirList[$i])
        __FileFindAllR($FileList, $aDirList[$i], $Mask, $AttribFilter)
    Next
    If $ProgressTitle <> '' Then ProgressOff()
    ReDim $FileList[$FileList[0]+1]
    Return $FileList
EndFunc
Func __FileFindAllR(ByRef $aFileList, $Path, $Mask, $AttribFilter)
    Dim $hndSearch_Files
    $hndSearch_Files = FileFindFirstFile($Path & '\' & $Mask)
    If $hndSearch_Files <> -1 Then
        $sFileName = FileFindNextFile($hndSearch_Files)
        While Not @error
            If _FileFilterAttrib($Path & '\' & $sFileName, $AttribFilter) And $sFileName <> '.' And $sFileName <> '..' Then
                $aFileList[0] = $aFileList[0] + 1
                $aFileList[$aFileList[0]] = $Path & '\' & $sFileName
            EndIf
            $sFileName = FileFindNextFile($hndSearch_Files)
        WEnd
    FileClose($hndSearch_Files)
    EndIf
EndFunc
Func _FileFilterAttrib($FileName, $Attrib)
    Dim $Return=0, $FileAttrib, $i, $ch
    If FileExists($FileName) Then
        $Return=-1
        $FileAttrib = FileGetAttrib($FileName)
        For $i = 1 to StringLen($Attrib)
            $ch = StringMid($Attrib,$i,1)
            If StringIsUpper($ch) Then
            ;This attribute must be on the list
                If not StringInStr($FileAttrib, $ch) then $Return = 0
            Else
            ;This attribute must not be on the list
                If StringInStr($FileAttrib, StringUpper($ch)) then $Return = 0
            EndIf
        Next
    EndIf
    Return $Return
EndFunc
;===============================================================================
;
; Function Name:    _FileGetTreeList
; Description:      Returns a recursive list of directories
; Parameter(s):     $Path = root path to begin the listing from
;                   $ProgressTitle = A title to put on a progress window.  Empty String = no progress window
; Requirement(s):   $Path is an existing directory
; Return Value(s):  A 1-based array containing the full path of all found directories
; Note:             Upon return, @Extended will contain a count of files (non-folders) found while searching for folders
; Author(s):        Mike Ratzlaff <mike@ratzlaff.org>
; Revision:         20050622A
;
;===============================================================================
;
Func _FileGetTreeList($Path, $ProgressTitle = @ScriptName)
    Dim $aDirList[100], $TotalFiles = 0
    If $ProgressTitle <> '' Then ProgressOn($ProgressTitle, 'Scanning directories...', '', -1, -1, 16)
    If _FileIsDir($Path) Then
        $TotalFiles = __FileGetTreeList($aDirList, $Path, $ProgressTitle)
    EndIf
    If $ProgressTitle <> '' Then ProgressOff()
    SetExtended($TotalFiles)
    ReDim $aDirList[$aDirList[0]+1]
    Return $aDirList
EndFunc
Func __FileGetTreeList(ByRef $aDirList, $Path, $ProgressTitle)
    Dim $hndSearch_Dirs, $FileCount
    If $ProgressTitle <> '' Then ProgressSet(random(99), $Path)
    ;Add the current directory on to the list
    $aDirList[0] = $aDirList[0] + 1
    If $aDirList[0] > UBound($aDirList) - 1 Then ReDim $aDirList[$aDirList[0] + 20]
    $aDirList[$aDirList[0]] = $Path
    
    ;Scan for more directories
    $hndSearch_Dirs = FileFindFirstFile($Path & '\*')
    If $hndSearch_Dirs <> -1 Then
        $sFileName = FileFindNextFile($hndSearch_Dirs)
        While Not @error
            If _FileIsDir($Path & '\' & $sFileName) Then
                ;Recurse into the directory, if it's not a special directory
                If $sFileName <> '.' And $sFileName <> '..' Then
                    $FileCount = $FileCount + __FileGetTreeList($aDirList, $Path & '\' & $sFileName, $ProgressTitle)
                EndIf
            Else
                ;Add to the filecount
                $FileCount = $FileCount + 1
            EndIf
            $sFileName = FileFindNextFile($hndSearch_Dirs)
        WEnd
    EndIf
    FileClose($hndSearch_Dirs)
    Return $FileCount
EndFunc
;===============================================================================
;
; Function Name:    _FileIsDir
; Description:      Returns true or false weather given file is a directory or not
; Parameter(s):     $Path
; Requirement(s):   
; Return Value(s):  0 = not a directory or does not exist, 1 = file exists and is a directory
; Author(s):        Mike Ratzlaff <mike@ratzlaff.org>
; Revision:         20050623A
;
;===============================================================================
;
Func _FileIsDir($Path)
    ;This function checkes to see if $FileName exists and if it is a Directory
    If StringInStr(FileGetAttrib($Path),'D') Then Return 1
    Return 0
EndFunc
Link to comment
Share on other sites

Thanks everyone. I am trying to open all autocad mechanical drawings, extract the BOM to an excel spreadsheet, then transfer the spreadsheet to SQL Server. Unfortanatelly I have over 5000 drawings and opening each file is time consuming and tedious. Looks like the open files will work perfectly. Thanks. Now I just have to perfect the script that opens the BOM dialog box, export as excel with a different name for each excel file. Again, THANK YOU ALL.

Link to comment
Share on other sites

One more question (I hope). how do you close the file after the shellexecute. The script opens autocad for each drawing in my test file. I have 3 so autocad opens 3 times. I want the drawing to open then close. THANKS IN ADVANCE.

$a = _FileSearch("*.dwg",1)
ShellExecute("C:\Program Files\Acadm 6\acad.exe")
If $a[0] > 0 Then
    For $i = 1 to $a[0]
         ;MsgBox(4096,"",$a[$i])
         ShellExecute($a[$i])
         WinClose($a[$i])
    Next
EndIf
;--------------------------------------------
Link to comment
Share on other sites

My script pause after opening the file. I am not sure why, any suggestions?

$a = _FileSearch("*.dwg",1)
;ShellExecute("C:\Program Files\Acadm 6\acad.exe")
If $a[0] > 0 Then
    For $i = 1 to $a[0]
         ;MsgBox(4096,"",$a[$i])
         ShellExecute($a[$i])
         Opt("WinWaitDelay",250)
         ;Opt("WinTitleMatchMode",4)
         Opt("WinDetectHiddenText",0)
         Opt("MouseCoordMode",0)
         WinWait("AutoCAD Mechanical Power Pack","\\etm02\users\Hedric")
         If Not WinActive("AutoCAD Mechanical Power Pack","\\etm02\users\Hedric") Then WinActivate("AutoCAD Mechanical Power Pack","\\etm02\users\Hedric")
         WinWaitActive("AutoCAD Mechanical Power Pack","\\etm02\users\Hedric")
         Send("{ALTDOWN}{ALTUP}n{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{RIGHT}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{ENTER}")
         WinWait("BOM","&Properties")
         If Not WinActive("BOM","&Properties") Then WinActivate("BOM","&Properties")
         WinWaitActive("BOM","&Properties")
         MouseMove(451,38)
         MouseDown("left")
         MouseUp("left")
         WinWait("Export","Save as &type:")
         If Not WinActive("Export","Save as &type:") Then WinActivate("Export","Save as &type:")
         WinWaitActive("Export","Save as &type:")
         MouseMove(309,249)
         MouseDown("left")
         MouseUp("left")
         MouseMove(281,293)
         MouseDown("left")
         MouseUp("left")
         MouseMove(266,221)
         MouseDown("left")
         MouseUp("left")
         Send($a[i])
         MouseMove(354,220)
         MouseDown("left")
         MouseMove(355,220)
         MouseUp("left")
         WinWait("BOM","&Properties")
         If Not WinActive("BOM","&Properties") Then WinActivate("BOM","&Properties")
         WinWaitActive("BOM","&Properties")
         MouseMove(468,482)
         MouseDown("left")
         MouseUp("left")
         MouseMove(348,480)
         MouseDown("left")
         MouseUp("left")

         ProcessClose("acad.exe")
         WinWait("AutoCAD","Save changes to \\et")
         If Not WinActive("AutoCAD","Save changes to \\et") Then WinActivate("AutoCAD","Save changes to \\et")
         WinWaitActive("AutoCAD","Save changes to \\et")
         MouseMove(160,96)
         MouseDown("left")
         MouseUp("left")


    Next
EndIf
;--------------------------------------------

Func _FileSearch($szMask,$nOption)
    $szRoot = ""
    $hFile = 0
    $szBuffer = ""
    $szReturn = ""
    $szPathList = "*"
    Dim $aNULL[1]

    If Not StringInStr($szMask,"\") Then
         $szRoot = @SCRIPTDIR & "\" ;put gates directory here
    Else
         While StringInStr($szMask,"\")
              $szRoot = $szRoot & StringLeft($szMask,StringInStr($szMask,"\"))
              $szMask = StringTrimLeft($szMask,StringInStr($szMask,"\"))
         Wend
    EndIf
    If $nOption = 0 Then
         _FileSearchUtil($szRoot, $szMask, $szReturn)
    Else
         While 1
              $hFile = FileFindFirstFile($szRoot & "*.*")
              If $hFile >= 0 Then
                   $szBuffer = FileFindNextFile($hFile)
                   While Not @ERROR
                        If $szBuffer <> "." And $szBuffer <> ".." And _
                             StringInStr(FileGetAttrib($szRoot & $szBuffer),"D") Then _
                             $szPathList = $szPathList & $szRoot & $szBuffer & "*"
                        $szBuffer = FileFindNextFile($hFile)
                   Wend
                   FileClose($hFile)
              EndIf
              _FileSearchUtil($szRoot, $szMask, $szReturn)
              If $szPathList == "*" Then ExitLoop
              $szPathList = StringTrimLeft($szPathList,1)
              $szRoot = StringLeft($szPathList,StringInStr($szPathList,"*")-1) & "\"
              $szPathList = StringTrimLeft($szPathList,StringInStr($szPathList,"*")-1)
         Wend
    EndIf
    If $szReturn = "" Then
         $aNULL[0] = 0
         Return $aNULL
    Else
         Return StringSplit(StringTrimRight($szReturn,1),"*")
    EndIf
EndFunc

Func _FileSearchUtil(ByRef $ROOT, ByRef $MASK, ByRef $RETURN)
    $hFile = FileFindFirstFile($ROOT & $MASK)
    If $hFile >= 0 Then
         $szBuffer = FileFindNextFile($hFile)
         While Not @ERROR
              If $szBuffer <> "." And $szBuffer <> ".." Then _
                   $RETURN = $RETURN & $ROOT & $szBuffer & "*"
              $szBuffer = FileFindNextFile($hFile)
         Wend
         FileClose($hFile)
     EndIf
EndFunc

Link to comment
Share on other sites

put a messagebox before and after

WinWait("AutoCAD Mechanical Power Pack","\\etm02\users\Hedric")

see if it ever finds that window....

That was the problem, couldn't find the file. Got it. You're the BEST. Thanks for all your help, (everyone), I got my code to work. You all saved me many many many months of work. I love AuotIt.

Link to comment
Share on other sites

  • 1 year later...

[bump ...]

I found the script above extremely useful.

However, not having success with one tweak, that of specifying a program to open the filetype. At the office, understandably, the computers are locked up pretty tight and I can't change that the Windows picture and fax viewer is the default for images. For the first time even Irfanview failed. Associating filetypes with it usu. is pretty foolproof and easy but the registry won't allow even that. However, all that's needed is to be able to get AI to work with the $app2openWith variable which will then mean that MS Paint opens all the bitmaps in the folder the script is in.

As is, this works at home but it does not work at the office because I cannot change the app. The script has some minor modifications, but all that's missing is getting that app variable in there somehow <g>:

#include <file.au3>

;==========================================
$extension    = ".bmp"
;------------------------------------------
$app2openWith = @SystemDir & "\mspaint.exe"
$path         = @ScriptDir & "\"
;==========================================


$FileArray = _FileListToArray($path, "*" & $extension,1)
For $i = 1 To $FileArray[0]
    ShellExecute($path & "\" & $FileArray[$i])
NextoÝ÷ دz{]¢)ටÉbëaÆ®¶­sbb33c´fÆT'&ÒôfÆTÆ7EFô'&b33c¶&÷VåvFÂb33c·FÂgV÷C²¢gV÷C²fײb33c¶WFVç6öâÃ
but that just gave me an error though it might be something simple in the syntax that I'm missing or don't know about.

Anyone know how to add the app to open with to the above script?

Thanks. <g>

Link to comment
Share on other sites

[bump ...]

I found the script above extremely useful.

However, not having success with one tweak, that of specifying a program to open the filetype. At the office, understandably, the computers are locked up pretty tight and I can't change that the Windows picture and fax viewer is the default for images. For the first time even Irfanview failed. Associating filetypes with it usu. is pretty foolproof and easy but the registry won't allow even that. However, all that's needed is to be able to get AI to work with the $app2openWith variable which will then mean that MS Paint opens all the bitmaps in the folder the script is in.

As is, this works at home but it does not work at the office because I cannot change the app. The script has some minor modifications, but all that's missing is getting that app variable in there somehow <g>:

#include <file.au3>

;==========================================
$extension    = ".bmp"
;------------------------------------------
$app2openWith = @SystemDir & "\mspaint.exe"
$path         = @ScriptDir & "\"
;==========================================


$FileArray = _FileListToArray($path, "*" & $extension,1)
For $i = 1 To $FileArray[0]
    ShellExecute($path & "\" & $FileArray[$i])
NextoÝ÷ دz{]¢)ටÉbëaÆ®¶­sbb33c´fÆT'&ÒôfÆTÆ7EFô'&b33c¶&÷VåvFÂb33c·FÂgV÷C²¢gV÷C²fײb33c¶WFVç6öâÃ
but that just gave me an error though it might be something simple in the syntax that I'm missing or don't know about.

Anyone know how to add the app to open with to the above script?

Thanks. <g>

This example is working on my xp.

#include <file.au3>
  
;==========================================
  $extension    = ".bmp"
;------------------------------------------
  $app2openWith = @SystemDir & "\mspaint.exe"
  $path      = @ScriptDir & "\"
;==========================================
  
  
  $FileArray = _FileListToArray($path, "*" & $extension,1)
  For $i = 1 To $FileArray[0]
      run($app2openWith  & ' "' & $path &  $FileArray[$i] & '"')
  Next
Edited by Malkey
Link to comment
Share on other sites

Absolutely marvellous! Tested it and works on my XP here at home, too. I'll test at the office on Monday.

This script, obviously, can be used to open all files of any type in the directory it's in. That can be changed to anything of course, even absolute paths. So it seems like it will be very versatile. And these particular instances of the script dealing with opening BMPs and GIFs get around MS Paint's inability to open more than one file simultaneously.

I tweaked the code a tiny bit. Besides testing for GIFs this time around, I decided to just put the extension itself. Seems to me that this would do away with possibility of forgetting to put that period (.) before the extension so that we'd just have to put something like 'gif' instead of '.gif':

#include <file.au3>
  
;==========================================
$extension    = "gif"
;------------------------------------------
$app2openWith = @SystemDir & "\mspaint.exe"
$path         = @ScriptDir & "\"
;==========================================
  
  
$FileArray = _FileListToArray($path, "*." & $extension,1)
For $i = 1 To $FileArray[0]
    run($app2openWith  & ' "' & $path &  $FileArray[$i] & '"')
Next

Thanks! <g>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...