Jump to content

Newb Question, wanna check fileexist, rename if so, and check ownership before copying


gh0stid
 Share

Recommended Posts

Hello, again ...

 

Ive been working a lot on a script lately .. unfortunately I just.. cannot figure to get it to work ( im no coder.. )
I start a new thread , cause the old one isoutdated, the code, have changed a lot since its creation

 

so far..

1 - I need to search for every files with specific extensions on C:\ G:\ H:\ drive and get their filesize. ---- Solved Using UDF _DirGetSizeEx

2- Output everything to log --- Solved too

3- Proceed to copy IF for drive G: ( another function ) @username match file ownership --- Not yet figured out.. 

Local $aFilesG = _DirGetSizeEx("\\fs1\groupes\DSTH\C - SGPI-SEFI\SGPI\PROJETS\T1200-T1299\T1206\4.0 Documents administratifs\Correspondance\", "*.nsf", 1)

If IsArray($aFilesG) Then
    ;FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFiles[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFiles[0][1]))
    _ProcessNSFCopyG($aFilesG)
EndIf


Func _ProcessNSFCopyG($aNSFFilesG)
    Local Static $x = 0
    Local $suffixe
$path = $aNSFFilesG[$i][0]

    For $i = 1 To $aNSFFilesG[0][0]
GetOwner($path)

Next
EndFunc


Func GetOwner()
    Local $computer = "."
    Local $wmi = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $computer & "\root\cimv2")

    Dim $res
    $res = $wmi.ExecQuery("ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" & $path & "'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner")

    For $val In $res
        Return $val.AccountName
    Next
EndFunc

Tried that.. no succes so far... and im sure its pretty obvious why but once again, cant figure it out . . ( it is only a TEST' not the actual code.. ) 

4- If ownership match, proceed to copy, to $storage, If upon copy FileExist, rename to $sFilename_1."extension of the file" --- having trouble here too ...

heres the code.. 

#include <Date.au3>
#include <Array.au3>
#include <File.au3>

Local $logfile = "c:\bulk\NSF.log"
Local $storage = "C:\bulk\backup_test\" & @UserName & "\"

Local $hLogFile = FileOpen($logfile, 1) ;1 = append au fichier, utiliser 2 si on veut overwrite


; ##### Pour le traitement sur c:\ g:\ h:\ ################################################################################
;creation des variables de recherche a l'aide de la fonction homemade _DirGetSizeEx
FileWriteLine($hLogFile, "[" & _Now() & "] Recherche des fichiers NSF NDK et INI sur C:\ G:\ et H:\ pour l'utilisateur " & @USERNAME)
Local $aFiles = _DirGetSizeEx("c:\", "*.nsf", 1)
Local $aFilesNDK = _DirGetSizeEx("c:\", "*.ndk", 1)
Local $aFilesINI = _DirGetSizeEx("c:\", "notes.ini", 1)
Local $aFilesG = _DirGetSizeEx("\\fs1\groupes\DSTH\C - SGPI-SEFI\SGPI\PROJETS\T1200-T1299\T1206\4.0 Documents administratifs\Correspondance\", "*.nsf", 1)
Local $aFilesH = _DirGetSizeEx("\\fs2\home\SAVA0002\notes\", "*.nsf", 1)

If IsArray($aFiles) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFiles[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFiles[0][1]))
    _ProcessNSFCopy($aFiles)
EndIf
If IsArray($aFilesINI) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFilesINI[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesINI[0][1]))
    _ProcessNSFCopy($aFilesINI)
EndIf
If IsArray($aFilesNDK) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFilesNDK[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesNDK[0][1]))
    _ProcessNSFCopy($aFilesNDK)
EndIf
If IsArray($aFilesG) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> G:\ " & $aFilesG[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesG[0][1]))
    _ProcessNSFCopyG($aFilesG)
EndIf
If IsArray($aFilesH) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> H:\ " & $aFilesH[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesH[0][1]))
    _ProcessNSFCopyH($aFilesH)
EndIf
; #################################################################################################################

FileWriteLine($hLogFile, "[" & _Now() & "] Fin")


Func _ProcessNSFCopy($aNSFFiles)

For $i = 1 To $aNSFFiles[0][0]
local Static $x = 0
local $Suffixe

    $SBPath = $aNSFFiles[$i][0]
    $SBType = 3


    If FileExists($SBPath) Then
    $Suffixe = "_" & $x
    $sFileName = _SBfpsplit($SBPath, $SBType)
    $sFileName = $sFileName & $Suffixe
Else
    $sFileName = _SBfpsplit($SBPath, $SBType)
    EndIf



        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFiles[$i][0] & " (" & _ReadableSize($aNSFFiles[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFiles[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
        $x += 1
Next

EndFunc

Func _ProcessNSFCopyINI($aNSFFilesINI)
For $i = 1 To $aNSFFilesINI[0][0]
    $SBPath = $aNSFFilesINI[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)


        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesINI[$i][0] & " (" & _ReadableSize($aNSFFilesINI[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesINI[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc

Func _ProcessNSFCopyNDK($aNSFFilesNDK)
For $i = 1 To $aNSFFilesNDK[0][0]
    $SBPath = $aNSFFilesNDK[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)


        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesNDK[$i][0] & " (" & _ReadableSize($aNSFFilesNDK[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesNDK[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc

Func _ProcessNSFCopyG($aNSFFilesG)
For $i = 1 To $aNSFFilesG[0][0]
    $SBPath = $aNSFFilesG[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)

        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesG[$i][0] & " (" & _ReadableSize($aNSFFilesG[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesG[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc

Func _ProcessNSFCopyH($aNSFFilesH)
For $i = 1 To $aNSFFilesH[0][0]
    $SBPath = $aNSFFilesH[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)

        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesH[$i][0] & " (" & _ReadableSize($aNSFFilesH[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesH[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc
FileClose($hLogFile)


; #FUNCTION#====================================================================================================================
; Name ..........: _DirGetSizeEx ; Description ...: Returns the size in bytes of a file list by extension.
; Syntax ........: _DirGetSizeEx($sDir[, $sMask = "*"[, $iFlag = 0]])
; Parameters ....: $sDir                - The directory to search in.
;                  $sMask               - [optional] Filter for results. Default is "*" (all).
;                                         Filter for result. Multiple filters must be separated by ";"
;                                         Use "|" to separate 3 possible sets of filters: "Include|Exclude|Exclude_Folders"
;                                             Include = Files/Folders to include (default = "*" [all])
;                                             Exclude = Files/Folders to exclude (default = "" [none])
;                                             Exclude_Folders = only used if $iRecur = 1 AND $iReturn <> 2 to exclude defined folders (default = "" [none])
;                  $iFlag               - [optional] 0 (default) = Returns the size
;                                                    1 = Extended mode is On -> returns an array that contains the file of each file (see Remarks).
;                                                    2 = Don't get the size of files in subdirectories (recursive mode is Off)
; Return values .: Success = The size in bytes, or a single dimension array
;                  Failure = -1 and sets the @error flag to 1 if the path doesn't exist.
; Author ........: jguinch
; Remarks .......: If you use the extended mode then the array returned from this function is a single dimension array containing the followingelements:
;                    $aArray[0][0] = Files count
;                    $aArray[0][1] = Total files size
;                    $aArray[1][0] = Full name of 1st file
;                    $aArray[1][1] = Size of 1st file
;                    $aArray[2][0] = Full name of 2nd file
;                    $aArray[2][1] = Size of 2nd file
;                    $aArray[n][1] = Size of nth file
;                    $aArray[n][1] = Size of nth file
;===============================================================================================================================
Func _DirGetSizeEx($sDir, $sMask = "*", $iFlag = 0); OK
    If NOT FileExists($sDir) Then Return SetError(1, 0, -1)
    If NOT StringInStr(FileGetAttrib($sDir), "D") Then Return SetError(1, 0, -1)

    Local $iExtMode = BitAND($iFlag, 1) > 0
    Local $iRecMode = NOT BitAND($iFlag, 2) > 0
    Local $aDirs[1] = [ StringRegExpReplace($sDir, "\\$", "") ]
    Local $iCountDir = 0, $iCountFile = 0, $n = 0, $iSize = 0, $iFullSize = 0
    Local $aFiles[1][2] = [[0]]
    Local $hSearch, $sFileName, $sRegexFilesInclude, $sRegexFilesExclude = "^$", $sRegexFoldersExclude = "^$"

    Local $sRegexMask = StringReplace( StringReplace( StringReplace($sMask, "|", "\|") , "?", "\E(?:.|.?$)\Q"), "*", "\E.*?\Q")
    Local $aFilters = StringSplit($sRegexMask, "\|", 3)

    $sRegexFilesInclude = "(?i)^(?:" & StringRegExpReplace(StringReplace($aFilters[0], ";", "|") , "([^|]+)", "\\Q$1\\E") & ")$"
    If UBound($aFilters) > 1 Then $sRegexFilesExclude = "(?i)^(?:" & StringRegExpReplace(StringReplace($aFilters[1], ";", "|") , "([^|]+)", "\\Q$1\\E") & ")$"
    If UBound($aFilters) > 2 Then $sRegexFoldersExclude = "(?i)^(?:" & StringRegExpReplace(StringReplace($aFilters[2], ";", "|") , "([^|]+)", "\\Q$1\\E") & ")$"

    While 1
        $hSearch = FileFindFirstFile( $aDirs[$n]  & "\*.*"  )
        If $hSearch <> -1 Then

            While 1
                $sFileName = FileFindNextFile($hSearch)
                If @error Then ExitLoop

                If @Extended Then
                    If NOT StringRegExp($sFileName, $sRegexFoldersExclude) Then
                        $iCountDir += 1
                        If $iCountDir >= UBound($aDirs) Then Redim $aDirs[UBound($aDirs) * 2]
                        $aDirs[$iCountDir] = $aDirs[$n] & "\" & $sFileName
                    EndIf
                Else
                    If StringRegExp($sFileName, $sRegexFilesInclude) AND NOT StringRegExp($sFileName, $sRegexFilesExclude) Then
                        $iSize = FileGetSize($aDirs[$n] &  "\" &$sFileName)
                        $iFullSize += $iSize
                        If $iExtMode Then
                            $iCountFile += 1
                            If $iCountFile >= UBound($aFiles) Then Redim $aFiles[UBound($aFiles) * 2][2]
                            $aFiles[$iCountFile][0] = $aDirs[$n] &  "\" &$sFileName
                            $aFiles[$iCountFile][1] = $iSize
                        EndIf
                    EndIf
                EndIf
            WEnd

            If NOT $iRecMode Then ExitLoop
        EndIf

        FileClose($hSearch)

        If $n = $iCountDir Then ExitLoop
        $n += 1
    WEnd

    If NOT $iExtMode Then Return $iFullSize

    Redim $aFiles[$iCountFile + 1][2]
    $aFiles[0][0] = $iCountFile
    $aFiles[0][1] = $iFullSize
    Return $aFiles
EndFunc

Func _ReadableSize($iSize, $decimalplaces = 2)
    Local $aUnites = [1024, "octets", "Ko", "Mo", "Go", "To"]
    For $i = 2 To UBound($aUnites) - 1
        If $iSize < $aUnites[0] Then ExitLoop
        $iSize /= $aUnites[0]
    Next
    Return Round($iSize, $decimalplaces) & " " & $aUnites[$i - 1]
EndFunc

;#FUNCTION# ====================================================================================================
; Name...........: _SBfpsplit
; Description ...: Splits a file path into Drive, path, filename, or extension.
; Syntax.........: _SBfpsplit($SBPath, $SBType);$SBpath (file path to evaluate) , $SBType (option)
; Parameters ....:
;|1 = Drive                 ex. D:
;|2 = Path                   ex. D:\1111\dir\file.txt
;|3 = File name          ex. file.txt
;|4 = Extension           ex. txt
;|5 = Drive letter only ex. D
; Author ........: Scott E. Brown ripandreplace@eset.com
; Modified.......:04/03/2009
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; _SBfpsplit("D:\1111\dir\file.txt, 1)
;
;$path = "D:\1111\dir\test.txt"
;ConsoleWrite(_SBfpsplit($path, 1) & @CRLF)
;ConsoleWrite(_SBfpsplit($path, 2) & @CRLF)
;ConsoleWrite(_SBfpsplit($path, 3) & @CRLF)
;ConsoleWrite(_SBfpsplit($path, 5) & @CRLF)
; ====================================================================================================
Func _SBfpsplit($SBPath, $SBType);$SBpath = file path to evaluate , $SBType = 1 for Drive, 2 for Path, 3 for File name, 4 for extension, 5 for drive letter only
    Local $SBfile, $SBSplit, $SBdrive, $SBfilepath, $SBnumber
    $SBSplit = StringSplit($SBPath, "\"); split into array
    $SBnumber = $SBSplit[0]; the number of strings returned
    $SBfilepath = ""
    for $1 = 1 to $SBnumber -1
        $SBfilepath = $SBfilepath & $SBSplit[$1] & "\"; path
    Next
    $SBfile = $SBSplit[($SBsplit[0])]; file
    $SBdrive = $SBSplit[1]; drive
    $SBfs = StringSplit($SBPath, "."); split into array
;MsgBox(4096, "Path", $SBSfs[0])
    if $SBfs[0] = 1 then
        $SBExt = ""; no extension found
    Else
        $SBExt = $SBfs[($SBfs[0])]; last . extentsion
    EndIf

    If $SBType = 1 then Return $SBdrive
    If $SBType = 2 then Return $SBfilepath
    If $SBType = 3 then Return $SBfile
    If $SBType = 4 then Return $SBExt
    If $SBType = 5 then Return StringLeft($SBdrive, 1)
EndFunc

 

Thank you ... 
btw. its really important for me, it for a Notes Migration of 1740 users... I dont want to do it by hand.. not, at all!

Edited by gh0stid
Link to comment
Share on other sites

  • Moderators

This is an example of what I use for determining ownership through WMI. Works on file or folder:

#include <MsgBoxConstants.au3>

$sFile = @DesktopDir & "\PDF Javascript.txt"
$oWMI = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & @ComputerName & "\root\cimv2")
    If Not IsObj($oWMI) Then Exit(MsgBox($MB_OK, "Returned error: " & @error, "Could not attach to WMI"))

$aItems = $oWMI.ExecQuery("ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" & $sFile & "'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner")
    For $sResult In $aItems
        ConsoleWrite($sResult.ReferencedDomainName & ", " & $sResult.AccountName & @CRLF)
    Next

 

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

This is an example of what I use for determining ownership through WMI. Works on file or folder:

#include <MsgBoxConstants.au3>

$sFile = @DesktopDir & "\PDF Javascript.txt"
$oWMI = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & @ComputerName & "\root\cimv2")
    If Not IsObj($oWMI) Then Exit(MsgBox($MB_OK, "Returned error: " & @error, "Could not attach to WMI"))

$aItems = $oWMI.ExecQuery("ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" & $sFile & "'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner")
    For $sResult In $aItems
        ConsoleWrite($sResult.ReferencedDomainName & ", " & $sResult.AccountName & @CRLF)
    Next

 

Unfortunately it wont work for my needs, I use Network Path in some case.. 

MsgBox('', '', _fileOwner(@AppDataDir))
MsgBox('', '', @UserName)
MsgBox('', '', @ScriptFullPath)

Func _fileOwner($varname)


    Dim $objSD
    Local $oWMIService = ObjGet("winmgmts:")
    Local $oFolderSecuritySettings = $oWMIService.Get("Win32_LogicalFileSecuritySetting='" & $varname & "'")
    Local $intRetVal = $oFolderSecuritySettings.GetSecurityDescriptor($objSD)

    If $intRetVal = 0 Then
        ;Local $objStr = $objSD.Owner.Domain & "\" & $objSD.Owner.Name;
        Local $objStr = $objSD.Owner.Name;
        Return($objStr)
    Else
        Return("Couldn't retrieve security descriptor.")
    EndIf
EndFunc

That. return the correct value. unfortunately, cannot get it to work on something else than @blablabla, Please take the time to see my code.
thank you !

Link to comment
Share on other sites

  • Moderators

In either case, your code or mine, you need to pull the information from WMI on the machine the file resides on. If this is a network share, you need to connect to that file server (which means you're going to need rights to it). This works just fine for me pulling from a network share using an account that has rights:

#include <MsgBoxConstants.au3>
$sServer = "<Server FQDN>"
$sFile = "C:\Share\File.txt"

$oWMI = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $sServer & "\root\cimv2")
    If Not IsObj($oWMI) Then Exit(MsgBox($MB_OK, "Returned error: " & @error, "Could not attach to WMI"))

$aItems = $oWMI.ExecQuery("ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" & $sFile & "'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner")
    For $sResult In $aItems
        ConsoleWrite($sResult.ReferencedDomainName & ", " & $sResult.AccountName & @CRLF)
    Next

 

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

The goal of that "part of the script" is to prevent duplicate files from being copying since multiple user will run it.

thank you for the help, but I might simply be ... too inexperienced or stupid to understand.

 

ive been struggling for a few day now.. figured how to get a list with _DirGetSizeEx, log everything, still need to manage possible filename duplicate. and ownership..

in fact ill be scanning network drive for file matching x/y criteria of my choice, put em in an array, if @username and ownership match proceed to copy to according $storage if not, proceed to the next file in array till end.

 

If i am needed to populate server FQDN .. apparentely I just wont be able to do it.. correct me if im wrong.

autoit program will be run by simple users. to figure what FILES do they own on drive G:  and then proceed to copy those files, only. it will not be ran by a superadmin or whatever similar.

Edited by gh0stid
Link to comment
Share on other sites

  • Moderators

Can you share what led you down the path of _DirGetSizeEX? It is a great script for its time, but Kafu wrote it back in 2009 and it hasn't been updated since. AutoIt has changed a lot since then. Can you detail what it is giving you that the built in DirGetSize (with some massaging) does not?

Looking at the code in your OP, you're pointing it at a share (\\fs1\groupes\DSTH\...). You are correct that you would need to connect to WMI on the file server and then do full path (C:\fs1\groupes\DSTH\...) As I mentioned, the big question is going to be whether you will be running the script under credentials that can access the location.

Edited by JLogan3o13

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

Sure: 

 

Ive been pointed to _DirGetSizeEX by jquinch on another french autoit forum. in fact, he provided me with his udf. then out of charity wrote most of the code and i just had to "adapt" my need.

I needed to be able to SEARCH for specific mask and return result in a array for future treament + get size of each file it returned matching the mask I choosen. ( for my knownledge, wich is limited. I didnt suceed at first with the basic function of AutoIt, plus im a bit in a hurry so unfortunately , i didnt have the "whole week" to try to figure it out .. i have zero experience in coding, i just.. try my best )

and for the answer of your question, That is exactely the point. we NEED users that run the autoit program to ONLY copy files on \\fs1\ ( no matter how deep it is in the directory tree ) wich OWNER of the file, MATCHES their @username retunred in AutoIT

Also need to be sure they do not overwrite duplicate files, but rename em instead 

 

#include <Date.au3>
#include <Array.au3>
#include <File.au3>


Local $logfile = "c:\bulk\NSF.log"
Local $storage = "C:\bulk\backup_test\" & @UserName & "\"

Local $hLogFile = FileOpen($logfile, 1) ;1 = append au fichier, utiliser 2 si on veut overwrite


; ##### Pour le traitement sur c:\ g:\ h:\ ################################################################################
;creation des variables de recherche a l'aide de la fonction homemade _DirGetSizeEx
FileWriteLine($hLogFile, "[" & _Now() & "] Recherche des fichiers NSF NDK et INI sur C:\ G:\ et H:\ pour l'utilisateur " & @USERNAME)
Local $aFiles = _DirGetSizeEx("c:\", "*.nsf", 1)
Local $aFilesNDK = _DirGetSizeEx("c:\", "*.ndk", 1)
Local $aFilesINI = _DirGetSizeEx("c:\", "notes.ini", 1)
Local $aFilesG = _DirGetSizeEx("\\fs1\groupes\DSTH\C - SGPI-SEFI\SGPI\PROJETS\T1200-T1299\T1206\4.0 Documents administratifs\Correspondance\", "*.nsf", 1)
Local $aFilesH = _DirGetSizeEx("\\fs2\home\SAVA0002\notes\", "*.nsf", 1)

;########################################################################
;#  SI un ARRAY CRÉER ON ECRIT LE LOG ET PROCEDE A LA FONCTION DE COPIE #
;####################################################################################################################
;# VALIDE POUR TOUS LES TYPE DE ARRAY, ICI ON AJOUTE OU RETIRE CE QUI EST SUPERFLUX POUR LES AUTRES ETABLISSEMENTS  #
;####################################################################################################################

If IsArray($aFiles) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFiles[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFiles[0][1]))
    _ProcessNSFCopy($aFiles)
EndIf

If IsArray($aFilesINI) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFilesINI[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesINI[0][1]))
    _ProcessNSFCopy($aFilesINI)
EndIf

If IsArray($aFilesNDK) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> C:\ " & $aFilesNDK[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesNDK[0][1]))
    _ProcessNSFCopy($aFilesNDK)
EndIf

If IsArray($aFilesG) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> G:\ " & $aFilesG[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesG[0][1]))
    _ProcessNSFCopyG($aFilesG)
EndIf

If IsArray($aFilesH) Then
    FileWriteLine($hLogFile, "[" & _Now() & "] -> H:\ " & $aFilesH[0][0] & " fichiers trouves pour une taille de " & _ReadableSize($aFilesH[0][1]))
    _ProcessNSFCopyH($aFilesH)
EndIf


FileWriteLine($hLogFile, "[" & _Now() & "] Fin")

;#################################################################################################################
;#  POUR TOUS CE QUI EST _PROCESSNFSCOPY * ON NE TOUCHE A RIEN, JE DOCUMENTE CELUI-CI, LES AUTRES SONT IDENTIQUES#
;#################################################################################################################

Func _ProcessNSFCopy($aNSFFiles)

;tentative de gestion de doublons, echec pour l'instant
For $i = 1 To $aNSFFiles[0][0]
local Static $x = 0
local $Suffixe

; on s'en sert pour isoler le FILENAME avec extension du PATH dans le array NSFFILES - ne pas toucher...
    $SBPath = $aNSFFiles[$i][0]
    $SBType = 3

;tentative de gestion de doublons, echec pour l'instant
    If FileExists($SBPath) Then
    $Suffixe = "_" & $x
    $sFileName = _SBfpsplit($SBPath, $SBType)
    $sFileName = $sFileName & $Suffixe
Else
    $sFileName = _SBfpsplit($SBPath, $SBType)
    EndIf


; écriture du log avec date et heure pour la grosseur des fichiers et leur noms. -- a fin de statistique et deboguage
        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFiles[$i][0] & " (" & _ReadableSize($aNSFFiles[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFiles[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
        $x += 1
Next

EndFunc

Func _ProcessNSFCopyINI($aNSFFilesINI)
For $i = 1 To $aNSFFilesINI[0][0]
    $SBPath = $aNSFFilesINI[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)


        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesINI[$i][0] & " (" & _ReadableSize($aNSFFilesINI[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesINI[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc

Func _ProcessNSFCopyNDK($aNSFFilesNDK)
For $i = 1 To $aNSFFilesNDK[0][0]
    $SBPath = $aNSFFilesNDK[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)


        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesNDK[$i][0] & " (" & _ReadableSize($aNSFFilesNDK[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesNDK[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc

Func _ProcessNSFCopyG($aNSFFilesG)
For $i = 1 To $aNSFFilesG[0][0]
    $SBPath = $aNSFFilesG[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)

        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesG[$i][0] & " (" & _ReadableSize($aNSFFilesG[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesG[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc

Func _ProcessNSFCopyH($aNSFFilesH)
For $i = 1 To $aNSFFilesH[0][0]
    $SBPath = $aNSFFilesH[$i][0]
    $SBType = 3
    $sFileName = _SBfpsplit($SBPath, $SBType)

        FileWriteLine($hLogFile, "[" & _Now() & "] Copie de " & $aNSFFilesH[$i][0] & " (" & _ReadableSize($aNSFFilesH[$i][1]) & ") => " & $storage & $sFileName&@CRLF)

        If FileCopy($aNSFFilesH[$i][0], $storage & $sFileName, 9) Then
            $sText = "Copie effectuee avec success"
        Else
            $sText = "ERREUR lors de la copie du fichier"
        EndIf
        FileWriteLine($hLogFile, "[" & _Now() & "] " & $sText)
    Next

EndFunc
FileClose($hLogFile)


; #FUNCTION#====================================================================================================================
; Name ..........: _DirGetSizeEx ; Description ...: Returns the size in bytes of a file list by extension.
; Syntax ........: _DirGetSizeEx($sDir[, $sMask = "*"[, $iFlag = 0]])
; Parameters ....: $sDir                - The directory to search in.
;                  $sMask               - [optional] Filter for results. Default is "*" (all).
;                                         Filter for result. Multiple filters must be separated by ";"
;                                         Use "|" to separate 3 possible sets of filters: "Include|Exclude|Exclude_Folders"
;                                             Include = Files/Folders to include (default = "*" [all])
;                                             Exclude = Files/Folders to exclude (default = "" [none])
;                                             Exclude_Folders = only used if $iRecur = 1 AND $iReturn <> 2 to exclude defined folders (default = "" [none])
;                  $iFlag               - [optional] 0 (default) = Returns the size
;                                                    1 = Extended mode is On -> returns an array that contains the file of each file (see Remarks).
;                                                    2 = Don't get the size of files in subdirectories (recursive mode is Off)
; Return values .: Success = The size in bytes, or a single dimension array
;                  Failure = -1 and sets the @error flag to 1 if the path doesn't exist.
; Author ........: jguinch
; Remarks .......: If you use the extended mode then the array returned from this function is a single dimension array containing the followingelements:
;                    $aArray[0][0] = Files count
;                    $aArray[0][1] = Total files size
;                    $aArray[1][0] = Full name of 1st file
;                    $aArray[1][1] = Size of 1st file
;                    $aArray[2][0] = Full name of 2nd file
;                    $aArray[2][1] = Size of 2nd file
;                    $aArray[n][1] = Size of nth file
;                    $aArray[n][1] = Size of nth file
;===============================================================================================================================
Func _DirGetSizeEx($sDir, $sMask = "*", $iFlag = 0); OK
    If NOT FileExists($sDir) Then Return SetError(1, 0, -1)
    If NOT StringInStr(FileGetAttrib($sDir), "D") Then Return SetError(1, 0, -1)

    Local $iExtMode = BitAND($iFlag, 1) > 0
    Local $iRecMode = NOT BitAND($iFlag, 2) > 0
    Local $aDirs[1] = [ StringRegExpReplace($sDir, "\\$", "") ]
    Local $iCountDir = 0, $iCountFile = 0, $n = 0, $iSize = 0, $iFullSize = 0
    Local $aFiles[1][2] = [[0]]
    Local $hSearch, $sFileName, $sRegexFilesInclude, $sRegexFilesExclude = "^$", $sRegexFoldersExclude = "^$"

    Local $sRegexMask = StringReplace( StringReplace( StringReplace($sMask, "|", "\|") , "?", "\E(?:.|.?$)\Q"), "*", "\E.*?\Q")
    Local $aFilters = StringSplit($sRegexMask, "\|", 3)

    $sRegexFilesInclude = "(?i)^(?:" & StringRegExpReplace(StringReplace($aFilters[0], ";", "|") , "([^|]+)", "\\Q$1\\E") & ")$"
    If UBound($aFilters) > 1 Then $sRegexFilesExclude = "(?i)^(?:" & StringRegExpReplace(StringReplace($aFilters[1], ";", "|") , "([^|]+)", "\\Q$1\\E") & ")$"
    If UBound($aFilters) > 2 Then $sRegexFoldersExclude = "(?i)^(?:" & StringRegExpReplace(StringReplace($aFilters[2], ";", "|") , "([^|]+)", "\\Q$1\\E") & ")$"

    While 1
        $hSearch = FileFindFirstFile( $aDirs[$n]  & "\*.*"  )
        If $hSearch <> -1 Then

            While 1
                $sFileName = FileFindNextFile($hSearch)
                If @error Then ExitLoop

                If @Extended Then
                    If NOT StringRegExp($sFileName, $sRegexFoldersExclude) Then
                        $iCountDir += 1
                        If $iCountDir >= UBound($aDirs) Then Redim $aDirs[UBound($aDirs) * 2]
                        $aDirs[$iCountDir] = $aDirs[$n] & "\" & $sFileName
                    EndIf
                Else
                    If StringRegExp($sFileName, $sRegexFilesInclude) AND NOT StringRegExp($sFileName, $sRegexFilesExclude) Then
                        $iSize = FileGetSize($aDirs[$n] &  "\" &$sFileName)
                        $iFullSize += $iSize
                        If $iExtMode Then
                            $iCountFile += 1
                            If $iCountFile >= UBound($aFiles) Then Redim $aFiles[UBound($aFiles) * 2][2]
                            $aFiles[$iCountFile][0] = $aDirs[$n] &  "\" &$sFileName
                            $aFiles[$iCountFile][1] = $iSize
                        EndIf
                    EndIf
                EndIf
            WEnd

            If NOT $iRecMode Then ExitLoop
        EndIf

        FileClose($hSearch)

        If $n = $iCountDir Then ExitLoop
        $n += 1
    WEnd

    If NOT $iExtMode Then Return $iFullSize

    Redim $aFiles[$iCountFile + 1][2]
    $aFiles[0][0] = $iCountFile
    $aFiles[0][1] = $iFullSize
    Return $aFiles
EndFunc

;################################################################
;# CONVERSION DES BYTES EN KO MO GO TO, PLUS CONVIVIABLE .......#
;################################################################

Func _ReadableSize($iSize, $decimalplaces = 2)
    Local $aUnites = [1024, "octets", "Ko", "Mo", "Go", "To"]
    For $i = 2 To UBound($aUnites) - 1
        If $iSize < $aUnites[0] Then ExitLoop
        $iSize /= $aUnites[0]
    Next
    Return Round($iSize, $decimalplaces) & " " & $aUnites[$i - 1]
EndFunc

;#FUNCTION# ====================================================================================================
; Name...........: _SBfpsplit
; Description ...: Splits a file path into Drive, path, filename, or extension.
; Syntax.........: _SBfpsplit($SBPath, $SBType);$SBpath (file path to evaluate) , $SBType (option)
; Parameters ....:
;|1 = Drive                 ex. D:
;|2 = Path                   ex. D:\1111\dir\file.txt
;|3 = File name          ex. file.txt
;|4 = Extension           ex. txt
;|5 = Drive letter only ex. D
; Author ........: Scott E. Brown ripandreplace@eset.com
; Modified.......:04/03/2009
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; _SBfpsplit("D:\1111\dir\file.txt, 1)
;
;$path = "D:\1111\dir\test.txt"
;ConsoleWrite(_SBfpsplit($path, 1) & @CRLF)
;ConsoleWrite(_SBfpsplit($path, 2) & @CRLF)
;ConsoleWrite(_SBfpsplit($path, 3) & @CRLF)
;ConsoleWrite(_SBfpsplit($path, 5) & @CRLF)
; ====================================================================================================
Func _SBfpsplit($SBPath, $SBType);$SBpath = file path to evaluate , $SBType = 1 for Drive, 2 for Path, 3 for File name, 4 for extension, 5 for drive letter only
    Local $SBfile, $SBSplit, $SBdrive, $SBfilepath, $SBnumber
    $SBSplit = StringSplit($SBPath, "\"); split into array
    $SBnumber = $SBSplit[0]; the number of strings returned
    $SBfilepath = ""
    for $1 = 1 to $SBnumber -1
        $SBfilepath = $SBfilepath & $SBSplit[$1] & "\"; path
    Next
    $SBfile = $SBSplit[($SBsplit[0])]; file
    $SBdrive = $SBSplit[1]; drive
    $SBfs = StringSplit($SBPath, "."); split into array
;MsgBox(4096, "Path", $SBSfs[0])
    if $SBfs[0] = 1 then
        $SBExt = ""; no extension found
    Else
        $SBExt = $SBfs[($SBfs[0])]; last . extentsion
    EndIf

    If $SBType = 1 then Return $SBdrive
    If $SBType = 2 then Return $SBfilepath
    If $SBType = 3 then Return $SBfile
    If $SBType = 4 then Return $SBExt
    If $SBType = 5 then Return StringLeft($SBdrive, 1)
EndFunc

 

Edited by gh0stid
Link to comment
Share on other sites

  • 3 weeks later...

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

×
×
  • Create New...