gh0stid

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

8 posts in this topic

#1 ·  Posted (edited)

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

Share this post


Link to post
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

 


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
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 !

Share this post


Link to post
Share on other sites

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

 


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

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

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

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

√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

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

Share this post


Link to post
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

  • Similar Content

    • cu0x
      By cu0x
      Hello guys,
       
      im trying to solved a problem that I have.
       
      Need to get some chinese text from an old Wise script, and in the wise file says f.e. Ù×÷ϵͳ¡£ ÇëÉý¼¶Ä. Is there any way to convert it to traditional chinese?
       
      Already tryied the following code...
       
      #include <MsgBoxConstants.au3> Example() Func Example() ; Define the string that will be converted later. ; NOTE: This string may show up as ?? in the help file and even in some editors. ; This example is saved as UTF-8 with BOM. It should display correctly in editors ; which support changing code pages based on BOMs. Local Const $sString = "Ù×÷ϵͳ¡£ ÇëÉý¼¶Ä" ; Temporary variables used to store conversion results. $dBinary will hold ; the original string in binary form and $sConverted will hold the result ; afte it's been transformed back to the original format. Local $dBinary = Binary(""), $sConverted = "" ; Convert the original UTF-8 string to an ANSI compatible binary string. $dBinary = StringToBinary($sString) ; Convert the ANSI compatible binary string back into a string. $sConverted = BinaryToString($dBinary) ; Display the resulsts. Note that the last two characters will appear ; as ?? since they cannot be represented in ANSI. DisplayResults($sString, $dBinary, $sConverted, "ANSI") ; Convert the original UTF-8 string to an UTF16-LE binary string. $dBinary = StringToBinary($sString, 2) ; Convert the UTF16-LE binary string back into a string. $sConverted = BinaryToString($dBinary, 2) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF16-LE") ; Convert the original UTF-8 string to an UTF16-BE binary string. $dBinary = StringToBinary($sString, 3) ; Convert the UTF16-BE binary string back into a string. $sConverted = BinaryToString($dBinary, 3) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF16-BE") ; Convert the original UTF-8 string to an UTF-8 binary string. $dBinary = StringToBinary($sString, 4) ; Convert the UTF8 binary string back into a string. $sConverted = BinaryToString($dBinary, 4) ; Display the resulsts. DisplayResults($sString, $dBinary, $sConverted, "UTF8") EndFunc ;==>Example ; Helper function which formats the message for display. It takes the following parameters: ; $sOriginal - The original string before conversions. ; $dBinary - The original string after it has been converted to binary. ; $sConverted- The string after it has been converted to binary and then back to a string. ; $sConversionType - A human friendly name for the encoding type used for the conversion. Func DisplayResults($sOriginal, $dBinary, $sConverted, $sConversionType) MsgBox($MB_SYSTEMMODAL, "", "Original:" & @CRLF & $sOriginal & @CRLF & @CRLF & "Binary:" & @CRLF & $dBinary & @CRLF & @CRLF & $sConversionType & ":" & @CRLF & $sConverted) EndFunc ;==>DisplayResults Thanks a lot!
    • Jibberish
      By Jibberish
      I am trying to add data to an array and I keep getting the error "Subscript used on non-accessible variable ".
      #include <array.au3> ; Includes, etc ~ ~ ~ Local $aOptionsArray[3] $aOptionsArray = CheckboxesAndRadioButtons() _ArrayDisplay($aOptionsArray) Func CheckboxesAndRadioButtons() ; Create Checkboxes and Radio Buttons and read the results ~ ~ ~ ; Radio Buttons to Array ; $aOptions[0] = $bTestSelectForever ; $aOptions[1] = $bTestSelect3Times ; $aOptions[2] = $bTestSelectOnce If $bSelect1 = 1 Then $aOptions[0] = "True" Else $aOptions[0] = "False" <<< This is where the error occurs. EndIf If $bSelect2 = 1 Then $aOptions[1] = "True" Else $aOptions[1] = "False" EndIf If $bSelect3 = 1 Then $aOptions[2] = "True" Else $aOptions[2] = "False" EndIf Return $aOptions EndFunc Is putting data into an array while in a If - Then - Else illegal?
    • nacerbaaziz
      By nacerbaaziz
      Hi dear
      I want create retractable bar using autoit
      I tried creating slider, but there's a problem with screen reader for the blind, so is there another retractable tape?
      It is advisable to not accept dragging with the keybord only with  mouse
      note:
      This bar is needed in the process of raising and lowering the volume
      I hope that there is a solution to do that
      i waiting your responses.
      Thanks in advance to all members and administrators
    • XanzyX
      By XanzyX
      Is there a function out there that will edit an existing file witha a "Save" and "Cancel" at the bottom?
      Example: Funcrion("TestFile.txt")
    • rte7
      By rte7
      Hello. We work with the BMC Remedy site to manage incidents and would like to automate the processes of clicking through this button code:
      <a href="javascript:" class="btn btn3d menu" style="top:21; left:184; width:21; height:21;"> <img class="btnimg" src="../../../../resources/images/mt_sprites.gif" alt="menu category issue" title=""> </a> I use firefox with mozrepl and autoit with include FF.au3
      I need your help
      I read the topic https://www.autoitscript.com/forum/topic/95595-ffau3-v0601b-10/ but I could not run the code from the listed commands
      ...
      It is necessary to press the button and from the list of the menu of cahorsations to select the item = "zone of trust abonent"
      Screen # 1 http://joxi.ru/52aJK7bh4a7ypA or below.
      1) Press button
      <a href="javascript:" class="btn btn3d menu" style="top:21; left:184; width:21; height:21;"> <img class="btnimg" src="../../../../resources/images/mt_sprites.gif" alt="menu category issue" title=""> </a>
      2) After pressing the button, I need to choose in this menu of 4 items to select an item called "zone of trust abonent", Screen # 2 - http://joxi.ru/p27gwQKHo71VQ2
      html code table items
      <table class="MenuTable" cellpadding="0" cellspacing="0" style="width: 179px;"> <tbody class="MenuTableBody"> <tr class="MenuTableRow"> <td class="MenuEntryName" nowrap="">zone of trust abonent</td> <td class="MenuEntryNoSub" arvalue="zone of trust abonent"></td> </tr> <tr class="MenuTableRow"><td class="MenuEntryName" nowrap="">zone of trust operator</td> <td class="MenuEntryNoSub" arvalue="zone of trust operator"></td> </tr> <tr class="MenuTableRow"><td class="MenuEntryName" nowrap="">zone of trust third operator</td> <td class="MenuEntryNoSub" arvalue="zone of trust third operator"></td></tr> <tr class="MenuTableRow"><td class="MenuEntryNameHover" nowrap="">No settings</td> <td class="MenuEntryNoSubHover" arvalue="No settings"></td> </tr> </tbody> </table>
       
       
      More in detail, I choose from the menu item "zone of trust abonent" Screen # 3 - http://joxi.ru/GrqVq4ZIQEPW4m

       
      3) The choice is made, Screen # 4 http://joxi.ru/v297w6aC3PovLr
      <textarea class="text sr " wrap="off" id="arid_WIN_0_1000002488" cols="20" maxlen="60" style="top:21; left:0; width:179; height:21;" armenu="CFG:PRC:CategoryHPD-Res-T1-Q" mstyle="2" arautoc="1" arautocmb="1" arautocak="0" arautoctt="400" rows="1"> </textarea>
       
      It's all. I would be very grateful to you =) !!!!!!!!!!
      Here are more detailed codes in the attachment. 
      button1.txt
      menu - table.txt
      all.txt