Enumerate files with case sensitivity in VBScript? - vbscript

I am using the following VBScript code snippet to enumerate all files in my c:\Scripts\ folder:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
ExecQuery("Select * from CIM_DataFile where Path = '\\Scripts\\'")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
Unfortunately objFile.Name returns the path in all lower-case. It is important to me to retrieve the case of all file names, i.e. NewFileOne.txt, should not be returned as newfileone.txt.
Is there a way to enumerate files with case-sensitivity in VBScript?

If you use the FileSystemObject, you will get back names with the case preserved
Files Collection (MSDN)
dim objFSO, path, fldr, f, msg
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set fldr = objFSO.GetFolder("C:\Scripts")
For Each f in fldr.Files
MsgBox f.name
Next

Unlike the CIM_DataFile.Name property, the FileName and Extension properties are case sensitive. So, if it's necessary for you to use WMI, you can retrieve the file name and extension separately:
WScript.Echo objFile.FileName & "." & objFile.Extension

Mike's solution is better, but here's A VERY UGLY alternative:
Using the shell exec execute the following command:
dir c:\scripts /B>file.txt
Now "file.txt" contains the file listed with proper casing.
Sorry, it's ugly but works.

Related

Cant move VBScript to another directory, it says "File not found"

Set objShell = CreateObject("Wscript.Shell")
strFile ="Lafarrel.vbs"
dim fso, fullPath
set fso = CreateObject("Scripting.FileSystemObject")
fullPath = fso.GetAbsolutePathName(strFile)
Wscript.Echo fullPath
Wscript.Sleep 1000
dim SourceLocation
dim DestinationLocation
dim FileName
SourceLocation = fullPath
DestinationLocation = """C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"""
FileName = "Lafarrel.vbs"
fso.MoveFile SourceLocation & "" & FileName, DestinationLocation & ""
Error starts at line 14
Maybe because the last line is incorrect?
Explain what I want VBScript to do:
I want this VBScript to find itself and then change to a different directory
Use Option Explicit, for everyones' sanity.
Wscript.Sleep 1000 is unnecessary.
This line has problems: DestinationLocation = """C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"""
This string-literal contains excessive double-quotes (VBScript uses double-double-quotes to escape individual double-quote chars, but strings containing only paths and filenames should not have internal delimiting quotes.
Also, %username% won't be expanded by FileSystemObject.MoveFile.
You will need to use WshShell.ExpandEnvironmentStrings first.
Also, C:\Users\%username%\AppData\Roaming\... is a poor choice of environment-variable'd-path as the Users directory might not be on C:\, and it might not even be named "Users".
Instead, you should use %APPDATA%.
obj prefixes are ugly and unnecessary.
Dim SourceLocation is redundant as it's an alias of fullPath. Ditto Dim FileName.
GetAbsolutePathName does not verify that the file actually exists: you'll get a runtime error if "Lafarrel.vbs" does not exist in the expected location when the script runs - so expect this situation and add an If guard.
So your code should look like this:
Option Explicit
Dim shell
Set shell = CreateObject( "WScript.Shell" ) ' aka WshShell
Dim fso
Set fso = CreateObject( "Scripting.FileSystemObject" )
Dim lafarrelVbsPath
lafarrelVbsPath = fso.GetAbsolutePathName( "Lafarrel.vbs" )
If fso.FileExists( lafarrelVbsPath ) Then
Dim destinationPath
destinationPath = "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\"
destinationPath = shell.ExpandEnvironmentStrings( destinationPath )
Wscript.Echo "Moving """ & lafarrelVbsPath & """ to """ & destinationPath & """..."
' When `destinationPath` ends with a slash, then "Lafarrel.vbs" won't be renamed (phew).
fso.MoveFile lafarrelVbsPath, destinationPath
Else
Wscript.Echo "Error: File not found: """ & lafarrelVbsPath & """."
End If
WScript.ScriptFullName returns the script path and filename in full.
This sample demonstrates a couple of things including a simple way to isolate the script folder (not really needed for your use case though).
If you save this exact script into your local %temp% folder, and create a folder '%temp%\temp two' (space in there) you can just run it.
Also you MUST use ExpandEnvironmentStrings method to use env vars in a string
strFileName = WScript.Scriptname
strCurrDir = Replace(WScript.ScriptFullName, WScript.Scriptname, "")
Set wshShell = CreateObject("WScript.Shell")
strDestination = wshShell.ExpandEnvironmentStrings("%temp%\temp two\") ' note the space, but no need to double-up quotes. You MUST use ExpandEnvironmentStrings method to use env vars in a string
Wscript.Echo "I am '" & strFileName & "' and I am in '" & strCurrDir & "'"
WScript.Echo "My full path and name in one is: " & WScript.ScriptFullName
' so for moving the file, no need to separate the path and filename, as 'WScript.ScriptFullName' contains all of it (dest file must NOT exist)
' no need to double-up quotes for destination path, as this is not batch and will treat the whole string as path including spaces
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile WScript.ScriptFullName, strDestination
WScript.Echo "I've now been moved to: " & strDestination

How to create text file and write to it in vbscript

I have the following script which locates all access files on a machine:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_DataFile Where Extension = 'mdb' OR Extension = 'ldb'")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
I'm very amateur when it comes to vbscript. Instead of Echoing to a dialog box, how do I have the script write each line out to a text file called "Results.txt"?
Also, as a bonus, how do I include the date modified of each Access file?
This is what you are looking for. In this part: ("C:\test.txt" ,8 , True), the first parameter is the path to the file. The second parameter is the iomode option. There are three options for the second parameter, 1 means for reading, 2 means for writing, and 8 means for appending. The third parameter is a boolean, true means a new file can be created if it doesn't exist. False means a new file cannot be created.
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
Set OutPutFile = FSO.OpenTextFile("C:\test.txt" ,8 , True)
OutPutFile.WriteLine("Writing text to a file")
Set FSO= Nothing
Simple Google search like "vbscript create and write to text file" will give you ocean of information on how to tackle this. Anyway here is simplest one to give you kick start.
'~ Create a FileSystemObject
Set objFSO=CreateObject("Scripting.FileSystemObject")
'~ Provide file path
outFile="YouFolderPath\Results.txt"
'~ Setting up file to write
Set objFile = objFSO.CreateTextFile(outFile,True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_DataFile Where Extension = 'mdb' OR Extension = 'ldb'")
For Each obj_File in colFiles
'Wscript.Echo objFile.Name 'Commented out
'~ Write to file
objFile.WriteLine obj_File.Name
Next
'~ Close the file
objFile.Close
Use the FileSystemObject's .CreateTextFile method to create a text file. Study the documentation/sample carefully.
A CIM_DataFile has a .LastAccess property.

Vbscript rename a remote folder

I'm working on a script that renames a folder on a remote pc. But it it's not working.
Iff I execute the script nothing happens. I use a modified version of the Hey Scripting Guy blog. If I use normal pathnames (c:\data) instead of remotepath names (\\"& strcomputer &"C$\data) it works. But if i use remote pathnames nothing happens.
Do you guys know whats wrong?
strComputer = "hostname"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
("Select * From Win32_Directory Where Name = '\\\\"& strComputer &"C$\\Data'")
For Each objFolder in colFolders
strNewName = objFolder.Name & ".old"
objFolder.Rename strNewName
Next
When you connect with WMI you don't use a UNC path with Win32_Directory (since it's local to that WMI repository).
So use ("Select * From Win32_Directory Where Name = 'C:\\Data'")
You should be able to accomplish your task using the FileSystemObject...
strComputer = "hostname"
strFolderName = "\\"& strComputer &"\C$\Data"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strFolderName) Then
Set objFolder = objFSO.GetFolder(strFolderName)
strNewName = objFolder.Name & ".old"
objFolder.Name = strNewName
End If

VB.Net - List files & subfolders from a specified Directory and save to a text document, and sort results

I am working on a project that requires me to search and list all files in a folder that could have multiple sub folders and write it to text documents.
Primarily the file extension i will be searching for is a .Doc, but I will need to list the other files found in said directory as well.
To make things slightly more difficult I want the text documents to be sorted by File type and another by Directory.
I do not know how possible this is, but I have search for methods online, but have as of yet found correct syntax.
Any help will be greatly appreciated.
I write this in the past, should server as a base for your version. I know it's not .NET, still I hope it helps something. It prompts the user for a path to scan, recurses into folders, and writes the file name, path, and owner into a CSV file. Probably really inefficient and slow, but does the job.
Main() ' trickster yo
Dim rootFolder 'As String
Dim FSO 'As Object
Dim ObjOutFile
Dim objWMIService 'As Object
Sub Main()
StartTime = Timer()
If Wscript.Arguments.Count = 1 Then ' if path provided with the argument, use it.
rootFolder = Wscript.Arguments.Item(0)
Else
rootFolder = InputBox("Give me the search path : ") ' if not, ask for it
End If
Set FSO = CreateObject("Scripting.FileSystemObject")
Set ObjOutFile = FSO.CreateTextFile("OutputFiles.csv")
Set objWMIService = GetObject("winmgmts:")
ObjOutFile.WriteLine ("Path, Owner") ' set headers
Gather (rootFolder)
ObjOutFile.Close ' close the stream
EndTime = Timer()
MsgBox ("Done. (ran for " & FormatNumber(EndTime - StartTime, 2) & "s.)")
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function Gather(FolderName)
On Error Resume Next
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = FSO.GetFolder(FolderName)
Set ObjFiles = ObjFolder.Files
For Each ObjFile In ObjFiles 'Write all files to output files
Set objFileSecuritySettings = _
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & ObjFile.Path & "'")
intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
If intRetVal = 0 Then
owner = objSD.owner.Domain & "\" & objSD.owner.Name
ObjOutFile.WriteLine (ObjFile.Path & ";" & owner) ' write in CSV format
End If
Next
Set ObjSubFolders = ObjFolder.SubFolders 'Getting all subfolders
For Each ObjFolder In ObjSubFolders
Set objFolderSecuritySettings = _
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & ObjFile.Path & "'")
intRetVal = objFolderSecuritySettings.GetSecurityDescriptor(objSD)
If intRetVal = 0 Then
owner = objSD.owner.Domain & "\" & objSD.owner.Name
ObjOutFile.WriteLine (ObjFolder.Path & ";" & owner) ' write in CSV format
End If
Gather (ObjFolder.Path)
Next
End Function

Scripting.FileSystemObject and ..lnk file

I'm looping in a folder to get all files inside it
Scripting.FileSystemObject doesn't seem to see that a file named ..lnk exist
is there a way to fix that?
thanks
Looping through a folder using WMI also seems to find *.lnk files. Try this example:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
ExecQuery("Select * from CIM_DataFile where Drive = 'C:' And Path = '\\Temp\\'")
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
I hope this helps.
/ Frank
it seem that I made a mistake while creating my test environment, I created a folder instead of a file.
now it's working.

Resources