Checking folders with VBS associators - vbscript

I need to find out is the path to the folder includes hidden folders or not.
Does anybody know how to do it? I have to use associators. Now my script only shows is the exact folder hidden or not and not checking the path to it.
Dim xdoc
Function CreateFolders(objFile)
Dim elem
Dim attr
Set elem = xdoc.CreateElement("Folder")
Set attr = xdoc.CreateAttribute("Description")
attr.Value = objFile.Description
elem.SetAttributeNode attr
Set CreateFolders = elem
End Function
Dim FilePath
Dim objFile
Dim root
Dim elem, elem1
Dim FilePath2
Set oFSO = CreateObject("Scripting.FileSystemObject")
If WScript.Arguments.Count > 0 Then
sFile = WScript.Arguments(0)
If oFSO.FileExists(sFile) Then
Set oFile = oFSO.GetFile(sFile)
sModify = oFile.DateLastModified
End If
End If
FilePath2 = WScript.Arguments(0)
Set xdoc = CreateObject("MSXML2.DOMDocument.6.0")
xdoc.AppendChild xdoc.CreateProcessingInstruction("xml", "version=""1.0"" encoding=""utf-8""")
FilePath = "C:\Users\User\Downloads\My123.xml"
Set root = xdoc.CreateElement("Folders")
xdoc.AppendChild root
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("SELECT * FROM Win32_Directory WHERE Name = '" & FilePath2 & "'")
For Each objFile In colFiles
Wscript.Echo objFile.Name & " " & "Status: " & objFile.Hidden
Set elem = CreateFolders(objFile)
root.AppendChild elem
Next
xdoc.Save FilePath

Related

Check if file is not at the same folder using WMI

I'm using script which is looking for specified file in local disk. When it finds the file, it renames/removes files which are close to specified file. (I mean at the same directory, etc)
Sample code:
Sub RenameFolder( oldName, newName )
Dim filesys
Set filesys = WScript.CreateObject("Scripting.FileSystemObject")
If filesys.FolderExists( oldName ) Then
filesys.MoveFolder oldName, newName
End If
End Sub
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_DataFile Where Filename = 'myfile' and Extension = 'exe'")
For Each objFile in colFiles
RenameFolder objFile.Drive & objFile.Path & "files\test", objFile.Drive & objFile.Path & "files\test_old"
I want to add a condition, which will check if in the same directory as myfile.exe, there is another file called otherfile.exe.
If it is there - don't do anything, else - rename specified folder like in the code above.
What you are looking for is the FileExists method. Here's how I'd suggest you use it in your code:
Sub RenameFolder( oldName, newName )
Dim filesys
Set filesys = WScript.CreateObject("Scripting.FileSystemObject")
If filesys.FolderExists( oldName ) Then
filesys.MoveFolder oldName, newName
End If
End Sub
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_DataFile Where Filename = 'myfile' and Extension = 'exe'")
For Each objFile in colFiles
If Not filesys.FileExists(objFile.Drive & objFile.Path & "otherfile.exe") Then
'No else clause needed since we are checking if the file _doesn't_ exist.
RenameFolder objFile.Drive & objFile.Path & "files\test", objFile.Drive & objFile.Path & "files\test_old"
End If
Next
EDIT: Changed my example to work directly in asker's code.

Using VBS to Backup a file

I managed to find this script to use and backup my files, this is a little more complicated then I need it to be.
I do not need to enter a backup path - from and too every time I run it however this is a handy option for other projects but I would like to backup from a set file path and save to a set file path to save time.
The other issue with this script is the Cancel button does not work, this is an issue I have had before and fixed but I cannot remember how to make the Cancel button function.
Option Explicit
Dim objFSO, strSourceFolder, strDestFolder, strExclusion, strPrompt
Set objFSO = CreateObject("Scripting.FileSystemObject")
strSourceFolder = InputBox("Enter the Source directory path you wish to backup")
strDestFolder = InputBox("Enter the Destination directory path you wish to backup your Data to... (C:/Backup, //Backup-Server/Remotebackup")
Wscript.Echo "Click (OK) to start the Backup!"
CopyFolderStructure strSourceFolder, strDestFolder, strExclusion
Function CopyFolderStructure(strSource, strDestination, strExcludedExt)
Const OVER_WRITE_FILES = True
Dim objDir, objFolder, objFiles, strCurExt, intX, arrExt, blnExclude
Set objDir = objFSO.GetFolder(strSource)
If Not objFSO.FolderExists(strDestination & "\" & objDir.Name) Then
objFSO.CreateFolder(strDestination & "\" & objDir.Name)
End If
If Not IsNoData(strExcludedExt) Then
arrExt = Split(strExcludedExt, ",")
blnExclude = False
End If
For Each objFiles In objFSO.GetFolder(strSource).Files
If Not IsNoData(strExcludedExt) Then
strCurExt = objFSO.GetExtensionName(objFiles.Name)
For intX = 0 To UBound(arrExt)
If LCase(strCurExt) = arrExt(intX) Then
blnExclude = True
Exit For
Else
blnExclude = False
End If
Next
If Not blnExclude Then
objFSO.CopyFile strSource & "\" & objFiles.Name, strDestination & "\" & objDir.Name & "\" & objFiles.Name, OVER_WRITE_FILES
End If
Else
objFSO.CopyFile strSource & "\" & objFiles.Name, strDestination & "\" & objDir.Name & "\" & objFiles.Name, OVER_WRITE_FILES
End If
Next
For Each objFolder In objFSO.GetFolder(strSource).SubFolders
CopyFolderStructure objFolder.Path, strDestination & "\" & objDir.Name, strExcludedExt
Next
End Function
Function BrowseForFolderDialogBox(strTitle)
Const WINDOW_HANDLE = 0
Const NO_OPTIONS = &H0001
Dim objShellApp
Dim objFolder
Dim objFldrItem
Dim objPath
Set objShellApp = CreateObject("Shell.Application")
Set objFolder = objShellApp.BrowseForFolder(WINDOW_HANDLE, strTitle , NO_OPTIONS)
If IsNoData(objFolder) Then
WScript.Echo "You choose to cancel. This will stop this script."
Wscript.Quit
Else
Set objFldrItem = objFolder.Self
objPath = objFldrItem.Path
BrowseForFolderDialogBox = objPath
Set objShellApp = Nothing
Set objFolder = Nothing
Set objFldrItem = Nothing
End If
End Function
Function IsNoData(varVal2Check)
On Error Resume Next
If IsNull(varVal2Check) Or IsEmpty(varVal2Check) Then
IsNoData = True
Else
If IsDate(varVal2Check) Then
IsNoData = False
Elseif varVal2Check = "" Then
IsNoData = True
ElseIf Not IsObject(varVal2Check) Then
IsNoData = False
Else
IsNoData = False
End If
End If
End Function
Wscript.Echo "Backup Has Completed Successfully"
Next code snippet could help (see Arguments Property (WScript Object), InputBox Function and MsgBox Function reference). Note that the Echo method behaves differently depending on which WSH engine you are using.
Option Explicit
Dim objFSO, strSourceFolder, strDestFolder, strExclusion, strPrompt
Dim iBut, sRes, sMes, objArgs
sRes = Wscript.ScriptName
sMes = vbCRLF & "(click (Cancel) button to discard)"
Set objArgs = WScript.Arguments
If objArgs.Count > 1 Then
strSourceFolder = objArgs( 0)
strDestFolder = objArgs( 1)
Else
strSourceFolder = "C:/DataToBackup"
strDestFolder = "D:/Backup"
strSourceFolder = InputBox( "Path you wish to backup" & sMes _
, "Source directory", strSourceFolder)
sRes = sRes & vbNewLine & "strSourceFolder """ & strSourceFolder & """"
If strSourceFolder = "" Then
strDestFolder = ""
Else
strDestFolder = InputBox( "Path you wish to backup your Data to" & sMes _
, "Destination directory", strDestFolder)
sRes = sRes & vbNewLine & "strDestFolder """ & strDestFolder & """"
End If
End If
If strDestFolder = "" Then
sRes = sRes & vbNewLine & "Backup Cancelled!"
Wscript.Echo sRes
Wscript.Quit
Else
iBut=MsgBox(sRes & sMes, vbOKCancel + vbQuestion _
, "Click (OK) to start the Backup!")
If iBut <> vbOK Then Wscript.Quit
End If
'''' for debugging only:
Wscript.Quit '''' for debugging only:
'''' for debugging only:
Set objFSO = CreateObject("Scripting.FileSystemObject")
CopyFolderStructure strSourceFolder, strDestFolder, strExclusion
'''''' and so on...

what is the best way to get the pst file sizes

Could someone please suggest the best way to grab the pst file sizes and write them out to the same text file next to the pst path.
Could someone please suggest the best way to grab the pst file sizes and write them out to the same text file next to the pst path.
Dim objNetworkSet, objFSO, objFolder, objShell, objTextFile, objFile, objWMISysEnv,ObjItem, objTextFileUNC
Dim strHomePath, strDirectory, strFile, strText, strComputerName,strDirectoryUNC,strFileUNC
dim colItems
On Error Resume Next
Set objNetwork = CreateObject("WScript.Network")
Set objOutlook = CreateObject("Outlook.Application")
Set objNS = objOutlook.GetNamespace("MAPI")
objNS.Logon "Mike", "" , False, True
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = WScript.CreateObject("WScript.Shell")
' Setting file names
strDirectory = "C:\Export"
strFile = "\" & ObjNetwork.Username & "-" & ObjNetwork.ComputerName & "-PST-Files.txt"
' Check to see if the file already exists exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder2 = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
objFile.Close
End If
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 8
' Opening text file
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
For Each objFolder2 In objNS.Folders
objTextFile.WriteLine(GetPSTpath(objFolder2.StoreID))
Next
Function GetPSTPath(input)
For i = 1 To Len(input) Step 2
strSubString = Mid(input,i,2)
If Not strSubString = "00" Then strPath = strPath & ChrW("&H" & strSubString)
Next
Select Case True
Case InStr(strPath,":\") > 0
GetPSTPath = Mid(strPath,InStr(strPath,":\")-1)
Case InStr(strPath,"\\") > 0
GetPSTPath = Mid(strPath,InStr(strPath,"\\"))
End Select
End Function
If your GetPSTPath() function is returning the proper paths to the files you seek, and you just want to write the file sizes along with the file paths, you can do this:
For Each objFolder2 In objNS.Folders
' Get the file path...
strPath = GetPSTpath(objFolder2.StoreID)
' Get the file's size...
intSize = objFSO.GetFile(strPath).Size
' Write both pieces of information to the output file...
objTextFile.WriteLine strPath & " = " & intSize
Next
Thanks for your help and suggestions. I came up with the following which grabs the users default Outlook profile launches Outlook, verifies the attached PSTs then outs to file, including username, PST location and size. The .MDC files are excluded which relate to Enterprise Vault local cache.
Dim objNetworkSet, objFSO, objFolder, objShell, objTextFile, objFile, objWMISysEnv,ObjItem, objTextFileUNC
Dim strHomePath, strDirectory, strFile, strText, strComputerName,strDirectoryUNC,strFileUNC
dim colItems
'On Error Resume Next
Set objNetwork = CreateObject("WScript.Network")
Set objOutlook = CreateObject("Outlook.Application")
Set objNS = objOutlook.GetNamespace("MAPI")
Set WSHShell = WScript.CreateObject("WScript.Shell")
DefaultOutlookProfile = WSHShell.RegRead("HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\DefaultProfile")
'MsgBox("DefaultOutlookProfile: " & DefaultOutlookProfile)
objNS.Logon DefaultOutlookProfile, "", False, True
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Setting file names
strDirectory = "\\NetworkShare\pstlog\"
strFile = ObjNetwork.Username & "-" & ObjNetwork.ComputerName & "-PST-Files.txt"
' Check to see if the file already exists exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder2 = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
objFile.Close
End If
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForWriting = 2
' Opening text file
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForWriting, True)
For Each strNS In objNS.Folders
'objTextFile.WriteLine(GetPSTpath(strNS.StoreID))
strPath2 = GetPSTpath(strNS.StoreID)
'MsgBox("strPath2: " & strPath2)
If Not strPath2 = "" And Not Right(strPath2, 4) = ".mdc" Then
' Get the file's size...
intSize = FormatNumber((objFSO.GetFile(strPath2).Size/1048576), 2) & " MB"
'intSize = intSize/1024 & " MB"
' Write both pieces of information to the output file...
objTextFile.WriteLine(ObjNetwork.Username & ", " & strPath2 & ", " & intSize)
End If
Next
Public Function GetPSTPath(input)
For i = 1 To Len(input) Step 2
strSubString = Mid(input,i,2)
If Not strSubString = "00" Then strPath = strPath & ChrW("&H" & strSubString)
Next
Select Case True
Case InStr(strPath,":\") > 0
GetPSTPath = Mid(strPath,InStr(strPath,":\")-1)
Case InStr(strPath,"\\") > 0
GetPSTPath = Mid(strPath,InStr(strPath,"\\"))
End Select
End Function
If err.number = vbEmpty then
Else WScript.echo "VBScript Error: " & err.number
End If

Return line number or subsequent text of a text file string search

I have a several text files that have thousands of lines each with this being an example of a typical line:
PCI\VEN_10EC&DEV_8168&REV_09 Realtek\5x64\FORCED\PCIe_5.810.1218.2012\ Netrtle.inf Realtek 1 12/18/2012,5.810.1218.2012 Realtek PCIe GBE Family Controller
The script I'm working on does a string search for that first segment of text:
PCI\VEN_10EC&DEV_8168&REV_09
My script narrows down which files have this string, but what I really need is for it then to return the next string on that same line:
Realtek\5x64\FORCED\PCIe_5.810.1218.2012\
Once I have this string I can continue on with the rest of the script which is just extracting the Realtek folder from a 7zip.
I've seen this has been done with other languages on Stack but I can't find anything for VBS. I could probably find an answer if I knew how to phrase the task better. I'd really appreciate some advise on grabbing that second string.
For background, this is the script I'm working on. It looks through all the text files in C:\scripts\ for a string returned by a WMI query for CompatibleID of device drivers with code 28 (no driver installed):
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Wscript.Shell")
Set objNet = CreateObject("WScript.Network")
Set objWMIService = GetObject("winmgmts:\\" & "." & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery _
("Select * from Win32_PnPEntity " _
& "WHERE ConfigManagerErrorCode = 28")
For Each objItem in colItems
Dim arrCompatibleIDs
aarCompatibleIDs = objItem.CompatibleID
for each objComp in aarCompatibleIDs
Dim FirstID
FirstID = objComp
Exit For
Next
Next
strSearchFor = firstID
objStartFolder = "C:\scripts"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
'Wscript.Echo objFile.Name
strFile = "C:\scripts\" & objFile.Name
set objFile = objFSO.getFile(strFile)
if objFile.size > 0 then
If InStr(objFSO.OpenTextFile(strFile).ReadAll, strSearchFor) > 0 Then
msgbox(objfile.name)
Else
WScript.Sleep (100)
End If
End If
Next
If you need to search for a fixed needle and a variable thread in a haystack, you can use some InStr()s or a RegExp. To get you started:
Dim sHaystack : sHaystack = Join(Array( _
"hay hay" _
, "fixed_needle variable_thread hay" _
, "hay hay" _
), vbCrLf)
Dim sNeedle : sNeedle = "fixed_needle" & " "
Dim nPosN : nPosN = Instr(sHaystack, sNeedle)
If 0 < nPosN Then
nPosN = nPosN + Len(sNeedle)
Dim nPosT : nPosT = Instr(nPosN, sHaystack, " ")
If 0 < nPosN Then
WScript.Echo "Instr()", qq(Mid(sHaystack, nPosN, nPosT - nPosN))
Else
WScript.Echo "no thread"
End If
Else
WScript.Echo "no needle"
End If
Dim reNT : Set reNT = New RegExp
reNT.Pattern = sNeedle & "(\S+) "
Dim oMTS : Set oMTS = reNT.Execute(sHayStack)
If 1 = oMTS.Count Then
WScript.Echo "RegExp ", qq(oMTS(0).SubMatches(0))
Else
WScript.Echo "no match"
End If
output:
Instr() "variable_thread"
RegExp "variable_thread"
If you change the haystack to
Dim sHaystack : sHaystack = Join(Array( _
"hay hay" _
, "fixed_needle no_variable_thread_hay" _
, "hay hay" _
), vbCrLf)
output:
Instr() "no_variable_thread_hay
hay"
no match
you see that there is more work needed to make the Instr() approach bulletproof.
Since your input file seems to be tab-separated, you could do something like this:
Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 28"
For Each entity In wmi.ExecQuery(qry)
For Each cid In entity.CompatibleID
firstID = cid
Exit For
Next
Next
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In objFSO.GetFolder(objStartFolder).Files
If f.Size > 0 Then
For line In Split(f.OpenAsTextStream.ReadAll, vbNewLine)
arr = Split(line, vbTab)
If arr(0) = firstID Then MsgBox arr(1)
Next
End If
Next
On a more general note, you shouldn't do stuff like this:
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFile = "C:\scripts\" & objFile.Name
set objFile = objFSO.getFile(strFile)
if objFile.size > 0 then
If InStr(objFSO.OpenTextFile(strFile).ReadAll, strSearchFor) > 0 Then
...
The Files collection already contains File objects, so it's utterly pointless to build a pathname from the object's properties (which BTW include a Path property that gives you the full path) only to obtain the exact same object you already have. Plus, file objects have a method OpenAsTextStream, so you can directly open them as text files without taking a detour like objFSO.OpenTextFile(f.Path).

Find all photographs taken on a certain date

If have the following VBScript for recursively finding all the files in a set of folders. I simply found this on the web somewhere and can't take credit for it.
fileExtension = ".jpg"
folderPath = "C:\Pictures"
computerName = "."
arrFIL = Array()
If Right(folderPath,1) = "\" Then folderPath = Left(folderPath,Len(folderPath)-1)
Set wmiObject = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & computerName & "\root\cimv2")
Set folderObject = wmiObject.Get("Win32_Directory='" & folderPath & "'")
EnumFolders folderObject, wmiObject, arrFIL
strFIL = UBound(arrFIL) + 1 & " files found with extension '" & fileExtension & "':" & vbCrLf & vbCrLf
For intFIL = 0 To UBound(arrFIL)
Set objFile = objFSO.GetFile(arrFIL(intFIL))
strFIL = strFIL & arrFIL(intFIL) & vbCrLf
Next
WScript.Echo strFIL
Sub EnumFolders(folderObject, wmiObject, arrFIL)
On Error Resume Next
Dim objSD1
Dim objSD2
Dim objFI1
Dim objFI2
Set objSD1 = wmiObject.ExecQuery("Associators of {Win32_Directory.Name='" & fold erObject.Name & "'} Where AssocClass=Win32_SubDirectory ResultRole=PartComponent")
For Each objSD2 in objSD1
EnumFolders objSD2, wmiObject, arrFIL
Next
On Error Goto 0
Set objFI1 = wmiObject.ExecQuery("Associators of {Win32_Directory.Name='" & folderObject.Name & "'} Where ResultClass=CIM_DataFile")
For Each objFI2 in objFI1
If Right(objFI2.Name,Len(fileExtension)) = fileExtension Then
intFIL = UBound(arrFIL) + 1
ReDim Preserve arrFIL(intFIL)
arrFIL(intFIL) = objFI2.Name
End If
Next
End Sub
What I need to do is run this against a bunch of folders, within C:\Pictures, and have it return all files where the Date Taken property of the photo is the 23rd of the month. Is this possible? How would I achieve this?
Thanks
I'd use the Shell.Application object instead of WMI:
Const Name = 0
Const DateTaken = 12
folderPath = "C:\Pictures"
Set re = New RegExp
re.Pattern = "[^0-9:./ ]"
re.Global = True
Traverse CreateObject("Shell.Application").Namespace(folderPath)
Sub Traverse(fldr)
For Each obj In fldr.Items
If obj.IsFolder Then
Traverse obj.GetFolder
ElseIf LCase(obj.Type) = "jpeg image" Then
If Day(re.Replace(fldr.GetDetailsOf(obj, DateTaken), "")) = 23 Then
WScript.Echo fldr.GetDetailsOf(obj, Name)
End If
End If
Next
End Sub

Resources