VBS Scripting Error - vbscript

I apologize in advance for my "newness" to vbs. I am trying to run this script to search for all pst files on my file server. At this point, I am getting this error:
searchpst.vbs(6, 26) Microsfot VBScript compilation error: Expected end of statement.
the script I am trying to run is of course named searchpst.vbs, and I know the (6, 26) is the line and charecter number of the error, but I cant seem to figure out what to do to fix it? Below is my script, and help is greatly appreciated!
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
strsql = "Select" * from CIM_DataFile Where Extension = '"pst"'"
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\test.csv",2,true)
For Each objFile in colFiles
Wfile.writeline(strComputer & " " & objFile.Drive & " " & objFile.Path & " " & objFile.FileName & "." & objFile.Extension & " " & objFile.FileSize)

I've reformatted the code for easier readability. The single apostrophe ' changes everything behind it into a comment, so it's not part of the code. So '"pst"'" isn't visible.
Actually, there are more problems than just that. That whole line is formatted incorrectly, and I think you've got a couple other lines out of order. It should look like this, I think:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
strsql = "Select * from CIM_DataFile Where Extension = 'pst'"
Set colFiles = objWMIService.ExecQuery(strsql)
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\test.csv",2,true)
For Each objFile in colFiles
Wfile.writeline(strComputer & " " & objFile.Drive & " " & objFile.Path & " " & objFile.FileName & "." & objFile.Extension & " " & objFile.FileSize)
Next

You need param list (), if you call a function to receive its return value; and _ continues a line - so change:
Set colFiles = objWMIService.ExecQuery _
strsql = "Select" * from CIM_DataFile Where Extension = '"pst"'"
to
strsql = "Select * from CIM_DataFile Where Extension = 'pst'"
Set colFiles = objWMIService.ExecQuery(strsql)
or:
Set colFiles = objWMIService.ExecQuery( _
"Select * from CIM_DataFile Where Extension = 'pst'")
After reading #Joe's (+1) answer, I tried to clean up the quoting in your SQL.

Related

Check if a file exists with a wildcard [duplicate]

Good morning all,
I have been trying to pull together a VBscript that takes a file path and a file name (that may have a wildcard in it) from the user when the script is exicuted. The script will then check the specified directory for a file that matches the provided file name and then looks at the last modified date to see if it was created/modified within a certain time frame (i.e. 6am plus or minus 5 minutes). It would then copy said file into a zip file.
So far I have been able to get the arguments working, and I have it setup to grab the current time, look at the files in the folder and match a hard coded filename to one in the folder. This is what I have thus far.
currentTime = Now()
filePath = Wscript.Arguments.Item(0)
fileName = Wscript.Arguments.Item(1)
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set directory = fileSystem.GetFolder(filePath)
For each file in directory.Files
If file.Name = fileName Then
Wscript.echo file.Name & " " & file.DateLastModified
end if
Next
I am a VBscript noob and I am looking forward to learning the way!
Cap3
If you use WMI, it supports wildcards.
Dim strPath
strFile = "*.*"
If WScript.Arguments.Count > 1 Then
strPath = WScript.Arguments.Item(0)
strFile = WScript.Arguments.Item(1)
Elseif WScript.Arguments.Count = 1 Then
strPath = WScript.Arguments.Item(0)
Else
End If
Set objFso = CreateObject("Scripting.FileSystemObject")
If Not objFso.FolderExists(strPath) Then
WScript.Echo "Folder path does not exist."
WScript.Quit
Else
'Remove any trailing slash
If Right(strPath, 1) = "\" Then
strPath = Left(strPath, Len(strPath) - 1)
End If
End If
Set objFso = Nothing
If Not IsNull(strPath) And strPath <> "" Then
strQuery = strPath & "\" & strFile
Else
strQuery = strFile
End If
strQuery = Replace(strQuery, "*", "%")
strQuery = Replace(strQuery, "?", "_")
strQuery = Replace(strQuery, "\", "\\")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * From CIM_DataFile Where FileName Like '" & strQuery & "'")
For Each objFile in colFiles
WScript.Echo "Access mask: " & objFile.AccessMask
WScript.Echo "Archive: " & objFile.Archive
WScript.Echo "Compressed: " & objFile.Compressed
WScript.Echo "Compression method: " & objFile.CompressionMethod
WScript.Echo "Creation date: " & objFile.CreationDate
WScript.Echo "Computer system name: " & objFile.CSName
WScript.Echo "Drive: " & objFile.Drive
WScript.Echo "8.3 file name: " & objFile.EightDotThreeFileName
WScript.Echo "Encrypted: " & objFile.Encrypted
WScript.Echo "Encryption method: " & objFile.EncryptionMethod
WScript.Echo "Extension: " & objFile.Extension
WScript.Echo "File name: " & objFile.FileName
WScript.Echo "File size: " & objFile.FileSize
WScript.Echo "File type: " & objFile.FileType
WScript.Echo "File system name: " & objFile.FSName
WScript.Echo "Hidden: " & objFile.Hidden
WScript.Echo "Last accessed: " & objFile.LastAccessed
WScript.Echo "Last modified: " & objFile.LastModified
WScript.Echo "Manufacturer: " & objFile.Manufacturer
WScript.Echo "Name: " & objFile.Name
WScript.Echo "Path: " & objFile.Path
WScript.Echo "Readable: " & objFile.Readable
WScript.Echo "System: " & objFile.System
WScript.Echo "Version: " & objFile.Version
WScript.Echo "Writeable: " & objFile.Writeable
Next
EDIT..........
You can use a WMI event script with the __InstanceCreationEvent to monitor for new file creation in a specific folder. It looks like this:
strSource = "C:\\somefilepath\\withdoubleshlashes"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & "rootcimv2")
Set colEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""" & strSource & """'")
Do While True
Set objEvent = colEvents.NextEvent()
copyFile(objEvent.TargetInstance.PartComponent)
Loop
For a full explanation, you can read Monitoring and Archiving Newly Created Files on my blog.
This answer uses Regular Expressions. To make it work it rewrites your pattern format into regular expression format. e.g. *.txt will become ^.*[.]txt$.
The following lists text files in C:\Temp last modified between 5:55 AM and 6:05 AM:
strPath = "C:\Temp"
strFile = "*.txt"
startTime = 555
endTime = 605
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(strPath)
Set files = folder.Files
Set re = New RegExp
re.IgnoreCase = true
re.Pattern = "^" + Replace(Replace(strFile, ".", "[.]"), "*", ".*") + "$"
For Each f in Files
Set matches = re.Execute(f.Name)
If matches.Count > 0 Then
HM = Hour(f.DateLastAccessed) * 100 + Minute(f.DateLastAccessed)
If HM >= startTime And HM <= endTime Then
WScript.Echo f.Name, f.DateLastAccessed
End If
End If
Next
References:
Regular Expression (RegExp) Object
Regular Expressions and Operators
Microsoft Beefs Up VBScript with Regular Expressions
Hey, Scripting Guy! Raising Eyebrows on Regular Expressions
For your example, the easiest way to do this is to use the inStr (In String)function. I find it works in 99% of my wild card tasks. So, in your example, instead of using:
If file.Name = fileName Then
use:
If inStr(file.Name, filename) Then
This doesn't actually allow for wildcards(*) as it won't find a match(with the asterisk in the argument), so you would need to strip the wildcard from the string and replace it with nothing (or just train the user to not use wildcards):
Replace(filename,"*", "")
However, the inStr function does allow for partial or full matches which makes it suitable for most wildcard tasks. Therefore, if your file name is pic.jpg, whether the user searches for:
pic or jpg or p or c or pi etc.
It will return a match. Keep in mind though, that the instr function returns a number where the match shows up in the string. So, if it doesn't create a match, the result will be 0. I've run into examples where NOT doesn't work or I've needed to use the full syntax which in this case would be:
If inStr(file.Name, filename)<>0 Then

Combine 2 VBScripts using the same file

Pretty new to scripting but i managed to put something together where i retrieve free disk space - formatted how i want. then the file is imported to SQL.
the error i am getting is that the output file is being used by the connection. how can i get this to run under one script without errors.. all help is appreciated.
`CONST strComputer = "."
AuditPath = "C:\Users\Pam\Desktop\Khalid.txt"
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=khalid;Data Source=GRIMLEY"
Set objFSO=CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(AuditPath,True)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery ("Select * from Win32_Volume")
Set objConn = CreateObject ("ADODB.Connection")
d = date()
ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=khalid;Data Source=GRIMLEY"
DIM objWMIService, objItem, colItems
DIM AuditPath, txt , strSQL , ConnectionString
txt = "Server" & vbtab & "DriveLetter" & vbtab & "DriveName" & vbtab & "Size" & vbtab & "Used" & vbtab & "Free" & vbtab & "% Free" & vbtab & "Date" & vbcrlf
Server = "ALL_IN_ONE_Final"
For Each objItem In colItems
ObjFile.Write Server & ","
objFile.write objItem.DriveLetter & ","
ObjFile.Write objItem.Label & ","
objFile.write Int(objItem.Capacity /1073741824)\1 & ","
objFile.write Int((objItem.Capacity - objItem.FreeSpace )/1073741824)\1 & ","
objFile.write Int (objItem.FreeSpace /1073741824)\1 & ","
objFile.write ((objItem.FreeSpace/objItem.Capacity) * 100)\1 & "," & vbcrlf
next
WScript.Sleep 8000
Set objConn = CreateObject ("ADODB.Connection")
objConn.Open ConnectionString
strSQL = strSQL & " BULK INSERT Server_Space"
strSQL = strSQL & " FROM 'C:\Users\Pam\Desktop\Khalid.txt' with"
strSQL = strSQL & " ( FIELDTERMINATOR =',', ROWTERMINATOR = '0x0a')"
objConn.Execute strSQL
objConn.Close
WScript.Quit()`

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.

VBscript to check for the existance of a file (with the ability to use a wildcard) within a certain time frame

Good morning all,
I have been trying to pull together a VBscript that takes a file path and a file name (that may have a wildcard in it) from the user when the script is exicuted. The script will then check the specified directory for a file that matches the provided file name and then looks at the last modified date to see if it was created/modified within a certain time frame (i.e. 6am plus or minus 5 minutes). It would then copy said file into a zip file.
So far I have been able to get the arguments working, and I have it setup to grab the current time, look at the files in the folder and match a hard coded filename to one in the folder. This is what I have thus far.
currentTime = Now()
filePath = Wscript.Arguments.Item(0)
fileName = Wscript.Arguments.Item(1)
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set directory = fileSystem.GetFolder(filePath)
For each file in directory.Files
If file.Name = fileName Then
Wscript.echo file.Name & " " & file.DateLastModified
end if
Next
I am a VBscript noob and I am looking forward to learning the way!
Cap3
If you use WMI, it supports wildcards.
Dim strPath
strFile = "*.*"
If WScript.Arguments.Count > 1 Then
strPath = WScript.Arguments.Item(0)
strFile = WScript.Arguments.Item(1)
Elseif WScript.Arguments.Count = 1 Then
strPath = WScript.Arguments.Item(0)
Else
End If
Set objFso = CreateObject("Scripting.FileSystemObject")
If Not objFso.FolderExists(strPath) Then
WScript.Echo "Folder path does not exist."
WScript.Quit
Else
'Remove any trailing slash
If Right(strPath, 1) = "\" Then
strPath = Left(strPath, Len(strPath) - 1)
End If
End If
Set objFso = Nothing
If Not IsNull(strPath) And strPath <> "" Then
strQuery = strPath & "\" & strFile
Else
strQuery = strFile
End If
strQuery = Replace(strQuery, "*", "%")
strQuery = Replace(strQuery, "?", "_")
strQuery = Replace(strQuery, "\", "\\")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * From CIM_DataFile Where FileName Like '" & strQuery & "'")
For Each objFile in colFiles
WScript.Echo "Access mask: " & objFile.AccessMask
WScript.Echo "Archive: " & objFile.Archive
WScript.Echo "Compressed: " & objFile.Compressed
WScript.Echo "Compression method: " & objFile.CompressionMethod
WScript.Echo "Creation date: " & objFile.CreationDate
WScript.Echo "Computer system name: " & objFile.CSName
WScript.Echo "Drive: " & objFile.Drive
WScript.Echo "8.3 file name: " & objFile.EightDotThreeFileName
WScript.Echo "Encrypted: " & objFile.Encrypted
WScript.Echo "Encryption method: " & objFile.EncryptionMethod
WScript.Echo "Extension: " & objFile.Extension
WScript.Echo "File name: " & objFile.FileName
WScript.Echo "File size: " & objFile.FileSize
WScript.Echo "File type: " & objFile.FileType
WScript.Echo "File system name: " & objFile.FSName
WScript.Echo "Hidden: " & objFile.Hidden
WScript.Echo "Last accessed: " & objFile.LastAccessed
WScript.Echo "Last modified: " & objFile.LastModified
WScript.Echo "Manufacturer: " & objFile.Manufacturer
WScript.Echo "Name: " & objFile.Name
WScript.Echo "Path: " & objFile.Path
WScript.Echo "Readable: " & objFile.Readable
WScript.Echo "System: " & objFile.System
WScript.Echo "Version: " & objFile.Version
WScript.Echo "Writeable: " & objFile.Writeable
Next
EDIT..........
You can use a WMI event script with the __InstanceCreationEvent to monitor for new file creation in a specific folder. It looks like this:
strSource = "C:\\somefilepath\\withdoubleshlashes"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & "rootcimv2")
Set colEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""" & strSource & """'")
Do While True
Set objEvent = colEvents.NextEvent()
copyFile(objEvent.TargetInstance.PartComponent)
Loop
For a full explanation, you can read Monitoring and Archiving Newly Created Files on my blog.
This answer uses Regular Expressions. To make it work it rewrites your pattern format into regular expression format. e.g. *.txt will become ^.*[.]txt$.
The following lists text files in C:\Temp last modified between 5:55 AM and 6:05 AM:
strPath = "C:\Temp"
strFile = "*.txt"
startTime = 555
endTime = 605
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(strPath)
Set files = folder.Files
Set re = New RegExp
re.IgnoreCase = true
re.Pattern = "^" + Replace(Replace(strFile, ".", "[.]"), "*", ".*") + "$"
For Each f in Files
Set matches = re.Execute(f.Name)
If matches.Count > 0 Then
HM = Hour(f.DateLastAccessed) * 100 + Minute(f.DateLastAccessed)
If HM >= startTime And HM <= endTime Then
WScript.Echo f.Name, f.DateLastAccessed
End If
End If
Next
References:
Regular Expression (RegExp) Object
Regular Expressions and Operators
Microsoft Beefs Up VBScript with Regular Expressions
Hey, Scripting Guy! Raising Eyebrows on Regular Expressions
For your example, the easiest way to do this is to use the inStr (In String)function. I find it works in 99% of my wild card tasks. So, in your example, instead of using:
If file.Name = fileName Then
use:
If inStr(file.Name, filename) Then
This doesn't actually allow for wildcards(*) as it won't find a match(with the asterisk in the argument), so you would need to strip the wildcard from the string and replace it with nothing (or just train the user to not use wildcards):
Replace(filename,"*", "")
However, the inStr function does allow for partial or full matches which makes it suitable for most wildcard tasks. Therefore, if your file name is pic.jpg, whether the user searches for:
pic or jpg or p or c or pi etc.
It will return a match. Keep in mind though, that the instr function returns a number where the match shows up in the string. So, if it doesn't create a match, the result will be 0. I've run into examples where NOT doesn't work or I've needed to use the full syntax which in this case would be:
If inStr(file.Name, filename)<>0 Then

copy files between a specified date range

I want to copy files from one folder to another which falls between a specific date range using VBS.
for example i want to copy files from 06/11/2009 to 06/12/2010.
How can I do that in VB script.
Is WMI an option? If so, here's a sample script based on the one from the Hey, Scripting Guy! article How Can I Delete All Files Older Than a Specified Date?:
strComputer = "."
strFolder = "C:\FromFolder"
strNewFolder = "C:\ToFolder"
strDateFrom = "20090611000000.000000+00" ' 06/11/2009
strDateTo = "20100612000000.000000+00" ' 06/12/2010
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colFiles = oWMI.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='" & strFolder & "'} WHERE " _
& "ResultClass = CIM_DataFile")
For Each oFile in colFiles
If oFile.CreationDate > strDateFrom And oFile.CreationDate < strDateTo Then
'WScript.Echo "Full path: " & oFile.Name
'WScript.Echo "Creation date: " & oFile.CreationDate
oFile.Copy strNewFolder & "\" & oFile.FileName & "." & oFile.Extension
oFile.Delete
End If
Next
Here's a slightly different variant where date checks are included in the WMI query:
strComputer = "."
strDateFrom = "20090611000000.000000+00" ' 06/11/2009
strDateTo = "20100612000000.000000+00" ' 06/12/2010
strNewFolder = "C:\ToFolder"
iFlags = 48
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colFiles = oWMI.ExecQuery( _
"SELECT * FROM CIM_DataFile" & _
" WHERE Drive = 'C:' AND Path = '\\FromFolder\\'" & _
" AND CreationDate >= '" & strDateFrom & "'" & _
" AND CreationDate <= '" & strDateTo & "'" _
,,iFlags)
For Each oFile in colFiles
'WScript.Echo "Full path: " & oFile.Name
'WScript.Echo "Creation date: " & oFile.CreationDate
oFile.Copy strNewFolder & "\" & oFile.FileName & "." & oFile.Extension
oFile.Delete
Next
A few notes:
The script is non-recursive, that is, it only moves files from the source folder itself and not its subfolders.
Dates are specified in the UTC format. More info about this format is in the article I linked to.
WMI doesn't include methods for moving files and folders, so the script copies then deletes the files.
You can use the FileSystemObject. The following will get the date a file was created:
Dim fso, myfile, d
Set fso = CreateObject("Scripting.FileSystemObject")
Set myfile = fso.GetFile("something.dat")
d = myfile.DateCreated
MsgBox d
Read more here.
Here is an example of how to loop through the files in a given folder. For each file, you can check the date, decide whether you like it, and if so copy the file.

Resources