none
Listar todos os arquivos de um pen-drive RRS feed

  • Pergunta

  • Boa tarde...
    Estou precisando criar um script que rode assim que o usuário colocar um pen-drive e me liste todos os arquivos e pastas contidos nesse pen-drive.
    quinta-feira, 15 de outubro de 2009 16:24

Respostas

  • Boa tarde,
    consegui alterar o último script que coloquei aqui de forma que ele consiga monitorar mais de um pen-driver conectado simultaneamente nas estações. Também consertei um erro que estava ocorrendo e eu não havia notado: Quando o script executava e não havia nenhum pen-driver conectado, o script simplesmente não terminava. Esse bug também foi resolvido.
    Segue o script abaixo:
    Const HKEY_LOCAL_MACHINE = &H80000002
    Const HARD_DISK = 2
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const ForReading2 = 1, ForWriting2 = 2, ForAppending2 = 8
    Const DeleteReadOnly = True
    DIM pctFreeSpace,strFreeSpace,strusedSpace,objDom,objNetwork, soft, retorno,objWMIService, objItem, colItems,strDriveType, strDiskSize
    strComputer = "."
    strMonth = Month(Date)
    If Len(strMonth) = 1 Then
     strMonth = "0" & strMonth
    End If
    strDay = Day(Date)
    If Len(strDay) = 1 Then
     strDay = "0" & strDay
    End If
    strYear = Year(Date)
    strPath = "C:\Documents and Settings\"
    Set objReg = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")
    strKeyPath = "System\CurrentControlSet\Services\USBStor\Enum"
    strValueName = "Count"
    Set objShell = CreateObject("Wscript.Shell")
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    Set objNetwork = CreateObject("WScript.Network")
    strPrograms = objShell.SpecialFolders("Desktop")
    Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    oReg.GetDWORDValue HKEY_Local_Machine,strKeyPath,strValueName,dwValue
    intRet1 = dwValue
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
    Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
    z=0
    If intRet1 = 0 Then
    WScript.Quit
    End If
    For Each objItem in colItems
     If objItem.Size <> 0 Then
      strDiskSize = (objItem.Size /1073741824)
      size = Left (strDiskSize,4) & " GB"
      If strDiskSize < 1 Then
        strDiskSize = (objItem.Size /1048576)
        Size = Left (strDiskSize,4) & " MB"
      End If
      strFreeSpace = (objItem.FreeSpace /1073741824)
      FreeSpace = Left (strFreeSpace,4) & " GB"
      If strFreeSpace < 1 Then
       strFreeSpace = (objItem.FreeSpace /1048576)
       FreeSpace = Left (strFreeSpace,4) & " MB"
      End If
      strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1073741824)
      Used = Left (strUsedSpace,4)& " GB"
      If strusedSpace < 1 Then
       strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1048576)
       Used = Left (strUsedSpace,4)& " MB"
      End If
      pctFreeSpace = ((objItem.FreeSpace / objItem.Size) * 1000)/10
      pFreeSpace = Left (pctFreeSpace,5)
      Letra = Left ( objItem.Name,3)
      z=z+1
     End If
     Volume = objItem.VolumeName
     Sistema = objItem.FileSystem
     Letra2 = Left ( Letra,1)
     objStartFolder = ""& Letra & ""
     If intRet1 <> 0 Then
      If Not objFSO.FileExists(strPrograms & "\USB.txt") Then
       FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
       Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
       Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
       For Each objComputer in colComputer
        WriteLog2 Letra2 & " - " & Volume & " conectado em " & now() & " Na Estação "& WshNetwork.ComputerName & " pelo usuário " & objComputer.UserName
       Next
      End If
      If z=0 Then
       Wscript.quit
      Else
       Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
       Set objFile = objFSO.CreateTextFile(strPrograms & "\USB.txt")
       If objFSO.FolderExists(""& Letra & "\Arquivos\") Then
        If objFSO.FileExists(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then
         Wscript.Quit
        Else
         FileLog = "\\server\share1\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt"
         Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
         Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
          For Each objComputer in colComputer
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
          WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
         Next
         WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
         WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
         WriteLog "Conteúdo :" & vbCrLf
         WriteLog "Iniciando verificação em " & Now () & vbCrLf
         WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
         WriteLog "Raiz:" & vbCrLf
         Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
         For Each objFile in colFiles
          objFile.Delete
         Next
         Set objFolder = objFSO.GetFolder(objStartFolder)
         Set colFiles = objFolder.Files
         ShowSubfolders objFSO.GetFolder(objStartFolder)
         Set objFile = objFSO.CreateTextFile(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb")
        End If
       Else
        If objFSO.FileExists(""& Letra & "\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then
         Wscript.Quit
        Else
         FileLog = "\\server\share1\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt"
         Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
         Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
          For Each objComputer in colComputer
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
          WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
         Next
         WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
         WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
         WriteLog "Conteúdo :" & vbCrLf
         WriteLog "Iniciando verificação em " & Now () & vbCrLf
         WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
         WriteLog "Raiz:" & vbCrLf
         Set objFolder = objFSO.GetFolder(objStartFolder)
         Set colFiles = objFolder.Files
         ShowSubfolders objFSO.GetFolder(objStartFolder)
         Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
         For Each objFile in colFiles
          objFile.Delete
         Next
         Set objFile = objFSO.CreateTextFile(""& Letra & strDay & "-" & strMonth & "-" & strYear & ".usb")
        End If
       End If
      End If
     Else
      If objFSO.FileExists(strPrograms & "\USB.txt") Then
       FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
       Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
       Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
       Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
        For Each objComputer in colComputer
        WriteLog2 "Pen Drive Desconectado em " & now() & " pelo usuário: " & objComputer.UserName
       Next
       objFSO.DeleteFile(strPrograms & "\USB.txt")
      End If
     End If
     strFolderName = ""& Letra & ""
     Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
     arrFolderPath = Split(strFolderName, "\")
     strNewPath = ""
     For i = 1 to Ubound(arrFolderPath)
      strNewPath = strNewPath & "\\" & arrFolderPath(i)
     Next
     strPath = strNewPath & "\\"
     Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
     r=0
     x=0
     u=0
     Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension <> 'usb'")
     For Each objFile in colFiles
      u=u+1
     Next
     strFolderName = ""& Letra & ""
     Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
     For Each objFolder in colSubfolders
      GetSubFolders strFolderName
     Next
     WriteLog "Total de " & u & " Arquivos e " & x & " Pastas" & vbCrLf 
     WriteLog "Verificação concluída em " & Now ()
     Next

     Sub ShowSubFolders(Folder)
      i=0
      For Each objFile In colFiles
       strComputer = "."
       strFile = folder.Path & "\" & objFile.Name
       WriteLog objFile.Name
       i=i+1
      Next
      If i = 0 Then
       WriteLog vbCrLf & "Diretório sem arquivos"
      Else
       WriteLog vbCrLf & i & " Arquivo(s)"
      End If
      WriteLog "-----------------------------------------------------------------------------------"
      For Each Subfolder In Folder.SubFolders
       WriteLog Subfolder.Path & vbCrLf
       Set objFolder = objFSO.GetFolder(Subfolder.Path)
       Set colFiles = objFolder.Files
       ShowSubFolders Subfolder
      Next
     End Sub
     
     Sub GetFolders(strFolderName)
      Set colSubfolders2 = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        arrFolderPath = Split(strFolderName, "\")
         strNewPath = ""
          For i = 1 to Ubound(arrFolderPath)
          strNewPath = strNewPath & "\\" & arrFolderPath(i)
         Next
        strPath = strNewPath & "\\"
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
         GetFolders strFolderName
       Next
     End Sub

     Sub GetSubFolders(strFolderName)
      Set colSubfolders2 = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        GetSubFolders strFolderName
        x=x+1
       Next
     End Sub

    Function WriteLog (Text)
    ObjFileAppending.WriteLine Text
    End Function

    Function WriteLog2 (Text)
     ObjFileAppending2.WriteLine Text
    End Function

    terça-feira, 10 de novembro de 2009 16:25

Todas as Respostas

  • Consegui elaborar o script abaixo que me lista os arquivos dos  pen-drives conectados em um computador, mas infelizmente não consegui com que ele me retornasse no fim do arquivo o total de arquivos e pastas encontrados.
    Alguém poderia me ajudar nisso?
    Obrigado.

    Const HARD_DISK = 2
    Dim objDom,objNetwork, objWMIService, objItem, colItems,strDriveType, strDiskSize
    StrComputer = "."

                         'Detectando a unidade correspondente ao pen drive
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colDisks = objWMIService.ExecQuery _
        ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
                         'Extraindo a letra da unidade  
    For Each objItem in colItems
        If objItem.Size <> 0 Then
          Letra = Left ( objItem.Name,3)
        End If
      Next
    objStartFolder = ""& Letra & ""
                    'criando o arquivo de log
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    FileLog = "\\Server\Share\" & WshNetwork.ComputerName & ".txt"
    ActionList = "no"
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
    Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
    Set objNetwork = CreateObject("WScript.Network")

                      'gravando o arquivo de log
    WriteLog "Conteúdo do Pen Drive conectado na unidade " & objStartFolder & " em " & Now ()
    WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
    WriteLog "Raiz:" & vbCrLf
    Set objFolder = objFSO.GetFolder(objStartFolder)
    Set colFiles = objFolder.Files
    ShowSubfolders objFSO.GetFolder(objStartFolder)
    Sub ShowSubFolders(Folder)
    i=0
       For Each objFile In colFiles
        strComputer = "."
        Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
        strFile = folder.Path & "\" & objFile.Name
          For Each objItem In colItems
            i=i+1
            WriteLog objFile.Name
          Next
       Next
    WriteLog vbCrLf & i & " Arquivo(s)"
    WriteLog "-----------------------------------------------------------------------------------"
    j=0
       For Each Subfolder In Folder.SubFolders
         j=j+1
         WriteLog Subfolder.Path & vbCrLf
         Set objFolder = objFSO.GetFolder(Subfolder.Path)
         Set colFiles = objFolder.Files
         ShowSubFolders Subfolder
       Next
    End Sub

                           'gravando resumo da utilização do pen drive
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
     For Each objItem in colItems
       DIM pctFreeSpace,strFreeSpace,strusedSpace
       strDiskSize = (objItem.Size /1073741824)
       size = Left (strDiskSize,4)
       strFreeSpace = (objItem.FreeSpace /1073741824)
       FreeSpace = Left (strFreeSpace,4)
       strUsedSpace = ((objItem.Size-objItem.FreeSpace)/1073741824)
       Used = Left (strUsedSpace,4)
       pctFreeSpace = ((FreeSpace / Size) * 1000)/10
       pFreeSpace = Left (pctFreeSpace,5)
       WriteLog "Capacidade: " & Size & " GB - em uso: " & Used & " GB - livre: " & FreeSpace & " GB - % livre: " & pFreeSpace
     Next

    Function WriteLog (Text)
    ObjFileAppending.WriteLine Text
    End Function

    sexta-feira, 16 de outubro de 2009 14:16
  • Boa tarde,
    consegui fazer com que no fim do log eu tenha a quantidade total de arquivos e pastas, vou editar esse script para que ele possa ser entendido melhor, pois devido a várias peculiaridades aqui da rede, ele acabou ficando com alguns detalhes específicos para a minha necessidade. Assim que terminar postarei aqui.
    quinta-feira, 29 de outubro de 2009 15:45
  • Bom, como havia dito anteriormente, segue abaixo o script. Como não entendo de programação, peço desculpas caso tenha linhas desnecessárias ou alguns erros, mas já testei aqui no trabalho alguns dias que me atendeu bem, não tendo nenhum problema.

    Const HKEY_CURRENT_USER = &H80000001
    Const HKEY_LOCAL_MACHINE = &H80000002
    Const HARD_DISK = 2
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const ForReading2 = 1, ForWriting2 = 2, ForAppending2 = 8
    Const DeleteReadOnly = True
    DIM pctFreeSpace,strFreeSpace,strusedSpace,objDom,objNetwork, soft, retorno,objWMIService, objItem, colItems,strDriveType, strDiskSize
    strComputer = "."
    strMonth = Month(Date)
    If Len(strMonth) = 1 Then
     strMonth = "0" & strMonth
    End If
    strDay = Day(Date)
    If Len(strDay) = 1 Then
     strDay = "0" & strDay
    End If
    strYear = Year(Date)
    strPath = "C:\Documents and Settings\"
    Set objReg = GetObject("winmgmts://" & strComputer & _
     "/root/default:StdRegProv")
    strKeyPath = "System\CurrentControlSet\Services\USBStor\Enum"
    strValueName = "Count"
    Set objShell = CreateObject("Wscript.Shell")
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    Set objNetwork = CreateObject("WScript.Network")
    strPrograms = objShell.SpecialFolders("Desktop")
    Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    oReg.GetDWORDValue HKEY_Local_Machine,strKeyPath,strValueName,dwValue
    intRet1 = dwValue
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
    Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
    z=0
    'Obtendo informações do pen drive
    For Each objItem in colItems
     If objItem.Size <> 0 Then
      strDiskSize = (objItem.Size /1073741824)
      size = Left (strDiskSize,4) & " GB"
      If strDiskSize < 1 Then
        strDiskSize = (objItem.Size /1048576)
        Size = Left (strDiskSize,4) & " MB"
      End If
      strFreeSpace = (objItem.FreeSpace /1073741824)
      FreeSpace = Left (strFreeSpace,4) & " GB"
      If strFreeSpace < 1 Then
       strFreeSpace = (objItem.FreeSpace /1048576)
       FreeSpace = Left (strFreeSpace,4) & " MB"
      End If
      strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1073741824)
      Used = Left (strUsedSpace,4)& " GB"
      If strusedSpace < 1 Then
       strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1048576)
       Used = Left (strUsedSpace,4)& " MB"
      End If
      pctFreeSpace = ((objItem.FreeSpace / objItem.Size) * 1000)/10
      pFreeSpace = Left (pctFreeSpace,5)
      Letra = Left ( objItem.Name,3)
      z=z+1
     End If
        Volume = objItem.VolumeName
        Sistema = objItem.FileSystem
    Next
    Letra2 = Left ( Letra,1)
    objStartFolder = ""& Letra & ""
    If intRet1 <> 0 Then
     If Not objFSO.FileExists(strPrograms & "\USB.txt") Then  'A
      FileLFileLog2 = "\\server\share1\" & WshNetwork.ComputerName & ".txt" 'B
      Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
      Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
      For Each objComputer in colComputer
       WriteLog2 Letra2 & " - " & Volume & " conectado em " & now() & " Na Estação "& WshNetwork.ComputerName & " pelo usuário " & objComputer.UserName
      Next
     End If
     If z=0 Then
      wscript.quit
     Else
      Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
       strComputer & "\root\default:StdRegProv")
      Set objFile = objFSO.CreateTextFile(strPrograms & "\USB.txt")'C
      If objFSO.FolderExists(""& Letra & "\Arquivos\") Then'D
       If objFSO.FileExists(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then 'G
        wscript.Quit
       Else
        FileLog = "\\server\share2\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt" 'E
        Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
        Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
         For Each objComputer in colComputer
          WriteLog "###################################################################################" 'F
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
         WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
        Next
        WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
        WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
        WriteLog "Conteúdo :" & vbCrLf
        WriteLog "Iniciando verificação em " & Now () & vbCrLf
        WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
        WriteLog "Raiz:" & vbCrLf
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")'H
        For Each objFile in colFiles
         objFile.Delete
        Next
        Set objFolder = objFSO.GetFolder(objStartFolder)
        Set colFiles = objFolder.Files
        ShowSubfolders objFSO.GetFolder(objStartFolder)
        Set objFile = objFSO.CreateTextFile(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb")'I
       End If
      Else
       If objFSO.FileExists(""& Letra & "\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then 'G
        Wscript.Quit
       Else
        FileLog = "\\server\share2\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt" 'E
        Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
        Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
         For Each objComputer in colComputer
          WriteLog "###############################################################################"
          WriteLog "###############################################################################"
          WriteLog "###############################################################################"
          WriteLog "###############################################################################"
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
         WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
        Next
        WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
        WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
        WriteLog "Conteúdo :" & vbCrLf
        WriteLog "Iniciando verificação em " & Now () & vbCrLf
        WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
        WriteLog "Raiz:" & vbCrLf
        Set objFolder = objFSO.GetFolder(objStartFolder)
        Set colFiles = objFolder.Files
        ShowSubfolders objFSO.GetFolder(objStartFolder)
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
        For Each objFile in colFiles
         objFile.Delete
        Next
        Set objFile = objFSO.CreateTextFile(""& Letra & strDay & "-" & strMonth & "-" & strYear & ".usb")'H
       End If
      End If
     End If
    Else
     If objFSO.FileExists(strPrograms & "\USB.txt") Then
      FileLog2 = "\\server\share1\" & WshNetwork.ComputerName & ".txt" 'B
      Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
      Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
      Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
      strComputer & "\root\default:StdRegProv")
       For Each objComputer in colComputer
       WriteLog2 "Pen Drive Desconectado em " & now() & " pelo usuário: " & objComputer.UserName
      Next
      objFSO.DeleteFile(strPrograms & "\USB.txt")
     End If
    End If
       
    Sub ShowSubFolders(Folder)
     For Each objFile In colFiles
      strComputer = "."
      strFile = folder.Path & "\" & objFile.Name
      WriteLog objFile.Name
      i=i+1
     Next
     If i = 0 Then
      WriteLog vbCrLf & "Diretório sem arquivos"
     Else
      WriteLog vbCrLf & i & " Arquivo(s)"
     End If
     WriteLog "-----------------------------------------------------------------------------------"
     For Each Subfolder In Folder.SubFolders
      WriteLog Subfolder.Path & vbCrLf
      Set objFolder = objFSO.GetFolder(Subfolder.Path)
      Set colFiles = objFolder.Files
      ShowSubFolders Subfolder
     Next
    End Sub
    strFolderName = ""& Letra & ""
    Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " _
    & "Where AssocClass = Win32_Subdirectory " _
    & "ResultRole = PartComponent")
    arrFolderPath = Split(strFolderName, "\")
    strNewPath = ""
    For i = 1 to Ubound(arrFolderPath)
     strNewPath = strNewPath & "\\" & arrFolderPath(i)
    Next
    strPath = strNewPath & "\\"
    Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
    r=0
    x=0
    '-------------------------------------------------------------------------------------
    Sub GetFolders(strFolderName)
     Set colSubfolders2 = objWMIService.ExecQuery _
     ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " _
     & "ResultRole = PartComponent")
     
      For Each objFolder2 in colSubfolders2
       strFolderName = objFolder2.Name
       arrFolderPath = Split(strFolderName, "\")
        strNewPath = ""
         For i = 1 to Ubound(arrFolderPath)
         strNewPath = strNewPath & "\\" & arrFolderPath(i)
        Next
       strPath = strNewPath & "\\"
       Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
        GetFolders strFolderName
      Next
    End Sub
    '--------------------------------------------------------------------------------------
    u=0
    Set colFiles = objWMIService.ExecQuery _
    ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension <> 'usb'")
    For Each objFile in colFiles
     u=u+1
    Next
    strFolderName = ""& Letra & ""
    Set colSubfolders = objWMIService.ExecQuery _
    ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " _
    & "ResultRole = PartComponent")

    For Each objFolder in colSubfolders
     GetSubFolders strFolderName
    Next
    '--------------------------------------------------------------------------------------
    Sub GetSubFolders(strFolderName)
     Set colSubfolders2 = objWMIService.ExecQuery _
      ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " _
      & "ResultRole = PartComponent")
      For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        GetSubFolders strFolderName
        x=x+1
      Next
    End Sub
    '--------------------------------------------------------------------------------------
    WriteLog "Total de " & u & " Arquivos e " & x & " Pastas" & vbCrLf 
    WriteLog "Verificação concluída em " & Now ()

    Function WriteLog (Text)
    ObjFileAppending.WriteLine Text
    End Function

    Function WriteLog2 (Text)
     ObjFileAppending2.WriteLine Text
    End Function


    Agora vou tentar explicar algumas particularidades:
    Em "A"  o script verifica se existe um arquivo chamado USB.txt no desktop do usuário, pois aqui na rede eu encontrei uma forma específica de verificar quando o usuário conecta e desconecta um pen drive e a presença desse arquivo é um parâmetro para essa monitoração; 
    Já em "B" eu defino aonde se localiza o arquivo de log para a monitoração do uso de pen-drivers;
    Em "C" é criado o arquivo que serve de parâmetro para a monitoração de conexão e desconexão de pen-drivers;
    Em "D" ocorre outra particularidade daqui da rede. Alguns pen-drivers que passam pela ADM da rede tem os seus sistemas de arquivo convertidos para NTFS e nesses é criada uma pasta chamada arquivos, após essa criação é negada para todos o direito de gravação na raiz do pen-drive, só sendo permitido gravar nessa pasta (arquivos). Esse procedimento tem por objetivo diminuir a proliferação de vírus através dos pen-drivers;
    Em "E" eu defino aonde se localiza o arquivo de log que listará o conteúdo dos pen-drivers;
    A função da linha em "F" é apenas para ficar mais fácil distinguir em uma listagem e outra;
    Em "G" é criado um arquivo cujo o nome é a data vigente. Optei por fazer isso para que a listagem dos arquivos não seja feita o tempo todo, mas no máximo uma vez por dia;
     Em "H" ,para evitar o acúmulo de arquivos ".USB" , todos os arquivos com essa extensão são apagados;
    E em "I" é criado um arquivo cujo o nome é a data vigente e a extensão é USB, assim no mesmo dia não será feita uma nova listagem do conteúdo desse pen-driver.

    OBS.
    Essa monitoração é feita por através de um outro script VBS, com o auxílio do comando schtasks, aonde eu entro com o nome da estação e o script copia esse script acima para a estação do usuário e cria um agendamento para executar o script a cada minuto.

    OBS2.
    Ainda estou tentando aprimorar mais um pouco esse script, pois ele apresenta erros quando mais de um pen-driver é conectado simultameamente na estação.

    sexta-feira, 6 de novembro de 2009 12:35
  • Boa tarde,
    consegui alterar o último script que coloquei aqui de forma que ele consiga monitorar mais de um pen-driver conectado simultaneamente nas estações. Também consertei um erro que estava ocorrendo e eu não havia notado: Quando o script executava e não havia nenhum pen-driver conectado, o script simplesmente não terminava. Esse bug também foi resolvido.
    Segue o script abaixo:
    Const HKEY_LOCAL_MACHINE = &H80000002
    Const HARD_DISK = 2
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const ForReading2 = 1, ForWriting2 = 2, ForAppending2 = 8
    Const DeleteReadOnly = True
    DIM pctFreeSpace,strFreeSpace,strusedSpace,objDom,objNetwork, soft, retorno,objWMIService, objItem, colItems,strDriveType, strDiskSize
    strComputer = "."
    strMonth = Month(Date)
    If Len(strMonth) = 1 Then
     strMonth = "0" & strMonth
    End If
    strDay = Day(Date)
    If Len(strDay) = 1 Then
     strDay = "0" & strDay
    End If
    strYear = Year(Date)
    strPath = "C:\Documents and Settings\"
    Set objReg = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")
    strKeyPath = "System\CurrentControlSet\Services\USBStor\Enum"
    strValueName = "Count"
    Set objShell = CreateObject("Wscript.Shell")
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    Set objNetwork = CreateObject("WScript.Network")
    strPrograms = objShell.SpecialFolders("Desktop")
    Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    oReg.GetDWORDValue HKEY_Local_Machine,strKeyPath,strValueName,dwValue
    intRet1 = dwValue
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
    Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
    z=0
    If intRet1 = 0 Then
    WScript.Quit
    End If
    For Each objItem in colItems
     If objItem.Size <> 0 Then
      strDiskSize = (objItem.Size /1073741824)
      size = Left (strDiskSize,4) & " GB"
      If strDiskSize < 1 Then
        strDiskSize = (objItem.Size /1048576)
        Size = Left (strDiskSize,4) & " MB"
      End If
      strFreeSpace = (objItem.FreeSpace /1073741824)
      FreeSpace = Left (strFreeSpace,4) & " GB"
      If strFreeSpace < 1 Then
       strFreeSpace = (objItem.FreeSpace /1048576)
       FreeSpace = Left (strFreeSpace,4) & " MB"
      End If
      strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1073741824)
      Used = Left (strUsedSpace,4)& " GB"
      If strusedSpace < 1 Then
       strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1048576)
       Used = Left (strUsedSpace,4)& " MB"
      End If
      pctFreeSpace = ((objItem.FreeSpace / objItem.Size) * 1000)/10
      pFreeSpace = Left (pctFreeSpace,5)
      Letra = Left ( objItem.Name,3)
      z=z+1
     End If
     Volume = objItem.VolumeName
     Sistema = objItem.FileSystem
     Letra2 = Left ( Letra,1)
     objStartFolder = ""& Letra & ""
     If intRet1 <> 0 Then
      If Not objFSO.FileExists(strPrograms & "\USB.txt") Then
       FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
       Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
       Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
       For Each objComputer in colComputer
        WriteLog2 Letra2 & " - " & Volume & " conectado em " & now() & " Na Estação "& WshNetwork.ComputerName & " pelo usuário " & objComputer.UserName
       Next
      End If
      If z=0 Then
       Wscript.quit
      Else
       Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
       Set objFile = objFSO.CreateTextFile(strPrograms & "\USB.txt")
       If objFSO.FolderExists(""& Letra & "\Arquivos\") Then
        If objFSO.FileExists(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then
         Wscript.Quit
        Else
         FileLog = "\\server\share1\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt"
         Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
         Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
          For Each objComputer in colComputer
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
          WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
         Next
         WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
         WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
         WriteLog "Conteúdo :" & vbCrLf
         WriteLog "Iniciando verificação em " & Now () & vbCrLf
         WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
         WriteLog "Raiz:" & vbCrLf
         Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
         For Each objFile in colFiles
          objFile.Delete
         Next
         Set objFolder = objFSO.GetFolder(objStartFolder)
         Set colFiles = objFolder.Files
         ShowSubfolders objFSO.GetFolder(objStartFolder)
         Set objFile = objFSO.CreateTextFile(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb")
        End If
       Else
        If objFSO.FileExists(""& Letra & "\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then
         Wscript.Quit
        Else
         FileLog = "\\server\share1\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt"
         Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
         Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
          For Each objComputer in colComputer
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "###################################################################################"
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
           WriteLog "                                                                                           "
          WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
         Next
         WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
         WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
         WriteLog "Conteúdo :" & vbCrLf
         WriteLog "Iniciando verificação em " & Now () & vbCrLf
         WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
         WriteLog "Raiz:" & vbCrLf
         Set objFolder = objFSO.GetFolder(objStartFolder)
         Set colFiles = objFolder.Files
         ShowSubfolders objFSO.GetFolder(objStartFolder)
         Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
         For Each objFile in colFiles
          objFile.Delete
         Next
         Set objFile = objFSO.CreateTextFile(""& Letra & strDay & "-" & strMonth & "-" & strYear & ".usb")
        End If
       End If
      End If
     Else
      If objFSO.FileExists(strPrograms & "\USB.txt") Then
       FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
       Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
       Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
       Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
        For Each objComputer in colComputer
        WriteLog2 "Pen Drive Desconectado em " & now() & " pelo usuário: " & objComputer.UserName
       Next
       objFSO.DeleteFile(strPrograms & "\USB.txt")
      End If
     End If
     strFolderName = ""& Letra & ""
     Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
     arrFolderPath = Split(strFolderName, "\")
     strNewPath = ""
     For i = 1 to Ubound(arrFolderPath)
      strNewPath = strNewPath & "\\" & arrFolderPath(i)
     Next
     strPath = strNewPath & "\\"
     Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
     r=0
     x=0
     u=0
     Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension <> 'usb'")
     For Each objFile in colFiles
      u=u+1
     Next
     strFolderName = ""& Letra & ""
     Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
     For Each objFolder in colSubfolders
      GetSubFolders strFolderName
     Next
     WriteLog "Total de " & u & " Arquivos e " & x & " Pastas" & vbCrLf 
     WriteLog "Verificação concluída em " & Now ()
     Next

     Sub ShowSubFolders(Folder)
      i=0
      For Each objFile In colFiles
       strComputer = "."
       strFile = folder.Path & "\" & objFile.Name
       WriteLog objFile.Name
       i=i+1
      Next
      If i = 0 Then
       WriteLog vbCrLf & "Diretório sem arquivos"
      Else
       WriteLog vbCrLf & i & " Arquivo(s)"
      End If
      WriteLog "-----------------------------------------------------------------------------------"
      For Each Subfolder In Folder.SubFolders
       WriteLog Subfolder.Path & vbCrLf
       Set objFolder = objFSO.GetFolder(Subfolder.Path)
       Set colFiles = objFolder.Files
       ShowSubFolders Subfolder
      Next
     End Sub
     
     Sub GetFolders(strFolderName)
      Set colSubfolders2 = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        arrFolderPath = Split(strFolderName, "\")
         strNewPath = ""
          For i = 1 to Ubound(arrFolderPath)
          strNewPath = strNewPath & "\\" & arrFolderPath(i)
         Next
        strPath = strNewPath & "\\"
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
         GetFolders strFolderName
       Next
     End Sub

     Sub GetSubFolders(strFolderName)
      Set colSubfolders2 = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        GetSubFolders strFolderName
        x=x+1
       Next
     End Sub

    Function WriteLog (Text)
    ObjFileAppending.WriteLine Text
    End Function

    Function WriteLog2 (Text)
     ObjFileAppending2.WriteLine Text
    End Function

    terça-feira, 10 de novembro de 2009 16:25
  • Notei alguns problemas com o script acima, a maioria relacionado com chaves de registros. Então fiz algumas alterações e cheguei ao script abaixo, que funcionou com o uso de até dois pen-drivers.

    Const HKEY_LOCAL_MACHINE = &H80000002
    Const HARD_DISK = 2
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const ForReading2 = 1, ForWriting2 = 2, ForAppending2 = 8
    Const DeleteReadOnly = True
    DIM pctFreeSpace,strFreeSpace,strusedSpace,objDom,objNetwork, soft, retorno,objWMIService, objItem, colItems,strDriveType, strDiskSize
    strComputer = "."
    strMonth = Month(Date)
    If Len(strMonth) = 1 Then
     strMonth = "0" & strMonth
    End If
    strDay = Day(Date)
    If Len(strDay) = 1 Then
     strDay = "0" & strDay
    End If
    strYear = Year(Date)
    strPath = "C:\Documents and Settings\"
    Set objReg = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")
    strKeyPath = "System\CurrentControlSet\Services\USBStor\"
    Set objShell = CreateObject("Wscript.Shell")
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    Set objNetwork = CreateObject("WScript.Network")
    strPrograms = objShell.SpecialFolders("Desktop")
    Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
    r=0
    For Each subkey In arrSubKeys
     If subkey = "Enum" Then
      r = r+1
      strKeyPath2 = "System\CurrentControlSet\Services\USBStor\Enum"
      strValueName = "Count"
      oReg.GetDWORDValue HKEY_Local_Machine,strKeyPath2,strValueName,dwValue
      intRet1 = dwValue
     End If
    Next
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
    Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
    If r > 0 Then
     If intRet1 = 1 Then
      If objFSO.FileExists(strPrograms & "\USB2.txt") Then
       FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
       Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
       Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
       Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
        For Each objComputer in colComputer
        WriteLog2 "Pen Drive Desconectado em " & now() & " pelo usuário: " & objComputer.UserName & " Restando um pen-drive conectado"
       Next
       objFSO.DeleteFile(strPrograms & "\USB2.txt")
      End If
     Else
      If intRet1 = 0 Then
       If objFSO.FileExists(strPrograms & "\USB2.txt") And objFSO.FileExists(strPrograms & "\USB.txt") Then
         FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
         Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
         Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
         Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
          For Each objComputer in colComputer
          WriteLog2 "Dois Pen Drives Desconectados em " & now() & " pelo usuário: " & objComputer.UserName
         Next
         objFSO.DeleteFile(strPrograms & "\USB.txt")
         objFSO.DeleteFile(strPrograms & "\USB2.txt")
       Else
        If objFSO.FileExists(strPrograms & "\USB.txt") Then
         FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
         Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
         Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
         Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
          For Each objComputer in colComputer
          WriteLog2 "Pen Drive Desconectado em " & now() & " pelo usuário: " & objComputer.UserName
         Next
         objFSO.DeleteFile(strPrograms & "\USB.txt")
        End If
        WScript.Quit
       End If
      End If
     End If
    Else
     If objFSO.FileExists(strPrograms & "\USB.txt") Then
      FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
      Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
      Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
      Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
       For Each objComputer in colComputer
       WriteLog2 "Pen Drive Desconectado em " & now() & " pelo usuário: " & objComputer.UserName
      Next
      objFSO.DeleteFile(strPrograms & "\USB.txt")
     End If
     WScript.Quit
    End If

    '--------------------verificando conexões de pen-drivers
    Set ObjFSO = CreateObject("Scripting.FileSystemObject")
    Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType=2")
    Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
    z=0
    For Each objItem in colItems
    t=0
     'contagem de pen-drivers
     If objItem.Size <> 0 Then
      strDiskSize = (objItem.Size /1073741824)
      size = Left (strDiskSize,4) & " GB"
      If strDiskSize < 1 Then
        strDiskSize = (objItem.Size /1048576)
        Size = Left (strDiskSize,4) & " MB"
      End If
      strFreeSpace = (objItem.FreeSpace /1073741824)
      FreeSpace = Left (strFreeSpace,4) & " GB"
      If strFreeSpace < 1 Then
       strFreeSpace = (objItem.FreeSpace /1048576)
       FreeSpace = Left (strFreeSpace,4) & " MB"
      End If
      strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1073741824)
      Used = Left (strUsedSpace,4)& " GB"
      If strusedSpace < 1 Then
       strUsedSpace = (((objItem.Size) - (objItem.FreeSpace))/1048576)
       Used = Left (strUsedSpace,4)& " MB"
      End If
      pctFreeSpace = ((objItem.FreeSpace / objItem.Size) * 1000)/10
      pFreeSpace = Left (pctFreeSpace,5)
      Letra = Left ( objItem.Name,3)
      z=z+1
     End If
     Volume = objItem.VolumeName
     Sistema = objItem.FileSystem
     Letra2 = Left ( Letra,1)
     objStartFolder = ""& Letra & ""
     If z=1 Then
      If Not objFSO.FileExists(strPrograms & "\USB.txt")Then
       FileLog2 = "\\server\share2\" & WshNetwork.ComputerName & ".txt"
       Set ObjFileRead2 = ObjFSO.opentextfile(FileLog2, ForReading2, True)
       Set ObjFileAppending2 = ObjFSO.opentextfile(FileLog2, ForAppending2, True)
       For Each objComputer in colComputer
        WriteLog2 Letra2 & " - " & Volume & " conectado em " & now() & " Na Estação "& WshNetwork.ComputerName & " pelo usuário " & objComputer.UserName
       Next
       Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
       Set objFile = objFSO.CreateTextFile(strPrograms & "\USB.txt")
      End If
     Else
      If z=2 Then
       If Not objFSO.FileExists(strPrograms & "\USB2.txt") Then
        For Each objComputer in colComputer
         WriteLog2 Letra2 & " - " & Volume & " conectado em " & now() & " Na Estação "& WshNetwork.ComputerName & " pelo usuário " & objComputer.UserName & " Segundo Pen-Driver conectado"
        Next
        Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
        Set objFile = objFSO.CreateTextFile(strPrograms & "\USB2.txt")
       End If
      End If
     End If 
     If z=0 Then
      Wscript.Sleep 1
     Else
      If objFSO.FolderExists(""& Letra & "\Arquivos\") Then
       If objFSO.FileExists(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then
        t=1
        Wscript.Sleep 1
       Else
        FileLog = "\\server\share1\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt"
        Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
        Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
         For Each objComputer in colComputer
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
         WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
        Next
        WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
        WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
        WriteLog "Conteúdo :" & vbCrLf
        WriteLog "Iniciando verificação em " & Now () & vbCrLf
        WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
        WriteLog "Raiz:" & vbCrLf
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
        For Each objFile in colFiles
         objFile.Delete
        Next
        Set objFolder = objFSO.GetFolder(objStartFolder)
        Set colFiles = objFolder.Files
        ShowSubfolders objFSO.GetFolder(objStartFolder)
        Set objFile = objFSO.CreateTextFile(""& Letra & "\Arquivos\" & strDay & "-" & strMonth & "-" & strYear & ".usb")
       End If
      Else
       If objFSO.FileExists(""& Letra & "\" & strDay & "-" & strMonth & "-" & strYear & ".usb") Then
        t=1
        WScript.Sleep 1
       Else
        FileLog = "\\server\share1\" & WshNetwork.ComputerName & " - " & Letra2 & " - " & Volume &".txt"
        Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
        Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
         For Each objComputer in colComputer
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "###################################################################################"
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
          WriteLog "                                                                                           "
         WriteLog "Descrição do Pen Drive conectado na unidade " & objStartFolder & " pelo usuário " & objComputer.UserName & vbCrLf
        Next
        WriteLog "Capacidade: " & Size & " - em uso: " & Used & " - livre: " & FreeSpace & " - % livre: " & pFreeSpace
        WriteLog "Sistema de arquivos: " & sistema & vbCrLf & "Nome do Volume: " & volume & vbCrLf
        WriteLog "Conteúdo :" & vbCrLf
        WriteLog "Iniciando verificação em " & Now () & vbCrLf
        WriteLog "-----------------------------------------------------------------------------------" & vbCrLf
        WriteLog "Raiz:" & vbCrLf
        Set objFolder = objFSO.GetFolder(objStartFolder)
        Set colFiles = objFolder.Files
        ShowSubfolders objFSO.GetFolder(objStartFolder)
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension = 'usb'")
        For Each objFile in colFiles
         objFile.Delete
        Next
        Set objFile = objFSO.CreateTextFile(""& Letra & strDay & "-" & strMonth & "-" & strYear & ".usb")
       End If
      End If
      'End If
      If t<>1 Then
       strFolderName = ""& Letra & ""
       Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       arrFolderPath = Split(strFolderName, "\")
       strNewPath = ""
       For i = 1 to Ubound(arrFolderPath)
        strNewPath = strNewPath & "\\" & arrFolderPath(i)
       Next
       strPath = strNewPath & "\\"
       Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
       r=0
       x=0
       u=0
       Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile Where Drive = '"& Letra & "' and Extension <> 'usb'")
       For Each objFile in colFiles
        u=u+1
       Next
       strFolderName = ""& Letra & ""
       Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder in colSubfolders
        GetSubFolders strFolderName
       Next
       WriteLog "Total de " & u & " Arquivos e " & x & " Pastas" & vbCrLf 
       WriteLog "Verificação concluída em " & Now ()
      End If
     End If
    Next

     Sub ShowSubFolders(Folder)
      i=0
      For Each objFile In colFiles
       strComputer = "."
       strFile = folder.Path & "\" & objFile.Name
       WriteLog objFile.Name
       i=i+1
      Next
      If i = 0 Then
       WriteLog vbCrLf & "Diretório sem arquivos"
      Else
       WriteLog vbCrLf & i & " Arquivo(s)"
      End If
      WriteLog "-----------------------------------------------------------------------------------"
      For Each Subfolder In Folder.SubFolders
       WriteLog Subfolder.Path & vbCrLf
       Set objFolder = objFSO.GetFolder(Subfolder.Path)
       Set colFiles = objFolder.Files
       ShowSubFolders Subfolder
      Next
     End Sub
     
     Sub GetFolders(strFolderName)
      Set colSubfolders2 = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        arrFolderPath = Split(strFolderName, "\")
         strNewPath = ""
          For i = 1 to Ubound(arrFolderPath)
          strNewPath = strNewPath & "\\" & arrFolderPath(i)
         Next
        strPath = strNewPath & "\\"
        Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Path = '" & strPath & "'")
         GetFolders strFolderName
       Next
     End Sub

     Sub GetSubFolders(strFolderName)
      Set colSubfolders2 = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='" & strFolderName & "'} " & "Where AssocClass = Win32_Subdirectory " & "ResultRole = PartComponent")
       For Each objFolder2 in colSubfolders2
        strFolderName = objFolder2.Name
        GetSubFolders strFolderName
        x=x+1
       Next
     End Sub

    Function WriteLog (Text)
    ObjFileAppending.WriteLine Text
    End Function

    Function WriteLog2 (Text)
     ObjFileAppending2.WriteLine Text
    End Function

    sexta-feira, 13 de novembro de 2009 12:06