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

 


When you're dead, you don't know you're dead - it's only difficult for those that know you. It's the same way when you're stupid...

My Scripts: SCCM UDFInclude Source with Compiled Script, Windows Firewall UDF

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

 


When you're dead, you don't know you're dead - it's only difficult for those that know you. It's the same way when you're stupid...

My Scripts: SCCM UDFInclude Source with Compiled Script, Windows Firewall UDF

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

When you're dead, you don't know you're dead - it's only difficult for those that know you. It's the same way when you're stupid...

My Scripts: SCCM UDFInclude Source with Compiled Script, Windows Firewall UDF

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

    • tcox8
      By tcox8
      Hello,
      Currently I am running a script that calls a powershell script. To read the results of that I am reading StdOut. I am parsing things accordingly but unfortunately it doesn't parse correctly all the time and I end up missing parts of the string or other problems. My question then is, what is the best results for reading what is returned when running a powershell script or something similar?
    • 31290
      By 31290
      Hi guys, 
      I'd like to write a piece of tool that would allow me to update a certain field in our Active Directory from a comma separated csv file composed like this:

      This file, automatically generated, can hold more than 10k lines.
      Thus, I need column A to be in one variable, column B in a second one and column C in a third one.
      I'm really missing this part as updating the AD is fairly easy once the 3 variable are populated. 
      I see things like this:
      Here's my attempts at the moment:
      #include <File.au3> #include <Array.au3> Global $csv_file = @DesktopDir & "\Book1.csv" Global $aRecords If Not _FileReadToArray($csv_file,$aRecords) Then MsgBox(4096,"Error", " Error reading log to Array error:" & @error) Exit EndIf For $x = 1 to $aRecords[0] Msgbox(0,'Record:' & $x, $aRecords[$x]) ; Shows the line that was read from file $csv_line_values = StringSplit($aRecords[$x], ",",1) ; Splits the line into 2 or more variables and puts them in an array ; _ArrayDisplay($csv_line_values) ; Shows what's in the array you just created. ; $csv_line_values[0] holds the number of elements in array ; $csv_line_values[1] holds the value ; $csv_line_values[2] holds the value ; etc Msgbox(0, 0, $csv_line_values[1]) Next Any help on this please? 
      Thanks in advance
      -31290-
    • SkysLastChance
      By SkysLastChance
      I keep losing the count of my $r varable when I go into the dropdown () function and call the same function.
      #include <Excel.au3> #include <AutoItConstants.au3> #include<GUIConstantsEx.au3> #include<EditConstants.au3> #include<GUIConstants.au3> Global $iBox, $oExcel, $oWorkbook, $r = 1, $x = 3 HowMany() Excel () Dropdown () Sleep (500) Func Dropdown () $list = GUICreate("Chart", 225, 80) $combobox = GUICtrlCreateCombo("Clinic 1", 10, 10, 120, 20) GUICtrlSetData(-1, "Clinic 2|Clinic 3|Clinic 4") $button = GUICtrlCreateButton("Select", 10, 40, 60, 20) GUISetState(@SW_SHOW) While 1 $guibox = GUIGetMsg() Select Case $guibox = $button Select Case GUICtrlRead($combobox) = "Clinic 1" GUIDelete($list) Auto () EndSelect Case $guibox = $GUI_EVENT_CLOSE EndSelect WEnd EndFunc Func HowMany() Local $iMsg While 1 ;~ Turn input into a number $iBox = Number(InputBox ("Regestration", "How Many Patients are there total?")) ;~ If user enters a string or cancels then get them to try again If $iBox = 0 Then $iMsg = MsgBox(1,'Regestration', 'Please enter a valid number') If $iMsg = 2 Then Exit Else ExitLoop EndIf WEnd EndFunc Func Excel() While ProcessExists("EXCEL.EXE") $ms = MsgBox(5,"","Process error. You have an Excel sheet open. You must close it in order to let this program work. Please close it now.") If $ms=2 Then Exit ;~ Doesn't require sleep since the script is paused by the MsgBox above ;~ Sleep(250) WEnd ;~ Shouldn't use Global Scope inside functions moved to top of script Local $sExcelFile = FileOpenDialog("Choose/Create Excel File", @ScriptDir, "(*.xlsx)") If FileExists($sExcelFile) Then ;~ Shouldn't use Global Scope inside functions moved to top of script $oExcel = _Excel_Open () $oWorkbook = _Excel_BookOpen($oExcel,$sExcelFile) ;this will open the chosen xls file. Else $oExcel = _Excel_Open() $oWorkbook = _Excel_BookNew($oExcel, 2);this is here to create the xls file if it does not exist. EndIf EndFunc Func Auto() Local $aArray1 = _Excel_RangeRead($oWorkbook) ;~ If $iBox is greater than no. of rows in $aArray then $iBox equals the number of rows in $aArray If $iBox > (UBound($aArray1) - 1) Then $iBox = UBound($aArray1) - 1 For $i = 2 To UBound($aArray1) - 1 ;$i =0 Start from row A If $aArray1[$i][1] = "" Then Continueloop $sR0 = $aArray1[$i][0] ;status $sR1 = $aArray1[$i][1] ;Last Name $sR2 = $aArray1[$i][2] ;First Name $sR3 = $aArray1[$i][3] ;DOB $sR4 = $aArray1[$i][4] ;Sex $sR5 = $aArray1[$i][5] ;Mailling Address $sR6 = $aArray1[$i][6] ;Zip $sR7 = $aArray1[$i][7] ;Phone # $sR8 = $aArray1[$i][8] ;Visit Reason $sR9 = $aArray1[$i][9] ;Insurance $sR10 = $aArray1[$i][10] ;Clinic $sR11 = $aArray1[$i][11] ;Provider $sR12 = $aArray1[$i][12] ;Appt Time $sR13 = $aArray1[$i][13] ;Appt Date WinWaitActive ("Untitled - Notepad") ControlSend("Untitled - Notepad", "", "", $sR1 & ',' & $sR2 & @CR) $r += 1 If $r > $iBox Then Exit Dropdown () Next EndFunc so the second time I choose clinic 1 I want it to go to the next row which would be Champ brett in my example excel.
       
      Test.xlsx
      Example Format.xlsx
    • StMaSi
      By StMaSi
      So, I have a text file like this...
      "Label", {left}, {top}, {width}, {height} "Label", {left}, {top}, {width}, {height} "Label", {left}, {top}, {width}, {height} "Label", {left}, {top}, {width}, {height} "Label", {left}, {top}, {width}, {height} What I'm attempting to do is read the data from this file, into an array, and use it to create checkboxes on a form like this...
      For $cb = 0 to 4 ; line numbers $Checkbox[$cb] = GUICtrlCreateCheckbox({label}, {left}, {top}, {width}, {height}) Next However, I can't figure out how to read the file into the array so as to be able to assign the data elements appropriately. I'm obviously missing something (or more than likely more than one something), but can't figure it out.
      Can anyone assist with this?
      Thanx.
       
    • Valnurat
      By Valnurat
      I hope my title is good enough.
      I'm using the ADO UDF and I have question regarding editing SQL records with this UDF.
      The owner of the UDF suggested an idea, but maybe there is another trix.