VBScript - Notification when file not created today - file

Goal: To run a VBScript that checks a folder daily, and reports if no files were saved to it that day. Ignore the files that exist from previous days.
Scenario: A logfile is created everyday in C:\Temp at 3am. This is what tells us that the system performed a task. If a log file isn't generated, then the task crashed. I wrote this to check the Temp folder for a file created today, and to email me if it doesn't exist.
Solution thus far:
option explicit
dim fileSystem, folder, file
dim path
path = "C:\Temp"
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(path)
for each file in folder.Files
if file.DateLastModified > dateadd("h", -24, Now) then
'WScript.Echo file.Name & " last modified at " & file.DateLastModified
else
SendEmail
'WScript.Echo "this should have sent an email."
end if
next
Function SendEmail()
'Send Email notification function here (this part works already)
End Function
Issue I am having:
I can't seem to wrap my head around a way to have the script ignore files in the folder from previous days.
In my test, I have C:\Temp populuated with a file modified today, and a file modified on 7/10/12. Because this scenario matches both the 'then' and the 'else' statement, it's doing both.
I think I just need a slight modification on the loop to tell it
- Ignore files not dated 'today'
- Send an email if no files exist today.
Any help would be awesome. I just can't seem to 'see' the answer.

You're close. The problem is is you were looping through and checking every single file. You need to only check if one file doesn't exist. I'm not that familiar with vbscript, so you may need to tweak this a bit, but what I did is add a variable found and initialized it to false. If you find a file created in past 24 hours, set it to true. once you're done looping, if it's still false, no files were modified in past 24 hours
option explicit
dim fileSystem, folder, file
dim path
Dim found
found = false
path = "C:\Temp"
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(path)
for each file in folder.Files
if file.DateLastModified > dateadd("h", -24, Now) then
found = true
end if
next
if (found = false) then
SendEmail
End If
Function SendEmail()
'Send Email notification function here (this part works already)
End Function

I would suggest first removing the time from the date check
Second Since you stated that the file is created each night I would check the DateCreated and not DateModified.
I modified your code below to add a variable Dim myDate and then set it to the previous day
Dim myDate
myDate = dateadd("d", -1, FormatDateTime(Now, 2))
I then changed the line
if file.DateCreated > myDate then
to look at the new variable.
Running this with the echo command worked as you described
and notified my of only the file that was created today.
option explicit
dim fileSystem, folder, file
dim path
path = "C:\Temp"
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Dim myDate
myDate = dateadd("d", -1, FormatDateTime(Now, 2))
Set folder = fileSystem.GetFolder(path)
for each file in folder.Files
if file.DateCreated > myDate then
'WScript.Echo file.Name & " last modified at " & file.DateCreated
SendEmail
'WScript.Echo "this should have sent an email."
end if
next
Function SendEmail()
'Send Email notification function here (this part works already)
End Function

This script:
Option Explicit
' config data, fixed
Const csPATH = "..\data"
' config data, computed, show use of DateValue() to cut off time
Dim dtCheck : dtCheck = DateValue(DateAdd("d", 0, Now))
WScript.Echo "dtCheck:", dtCheck
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim bFound : bFound = False ' assume no up-to-date file found
Dim oFile
For Each oFile In oFS.GetFolder(csPATH).Files
WScript.Echo "Check:", DateValue(oFile.DateLastModified), oFile.Name
If DateValue(oFile.DateLastModified) = dtCheck Then
WScript.Echo "Found:", DateValue(oFile.DateLastModified), oFile.Name
WScript.Echo "no need for further loopings"
bFound = True
Exit For
End If
Next
If Not bFound Then
WScript.Echo "Sending email ..."
End If
output 1:
dtCheck: 12.07.2012
Check: 11.07.2012 11434579.kpf
Check: 11.07.2012 11434579.notes
Check: 11.07.2012 11434579-UE15.prj
Sending email ...
output 2:
dtCheck: 12.07.2012
Check: 11.07.2012 11434579.kpf
Check: 11.07.2012 11434579.notes
Check: 11.07.2012 11434579-UE15.prj
Check: 12.07.2012 11458011.notes
Found: 12.07.2012 11458011.notes
no need for further loopings
expands on Ghost's approach by breaking/exiting the loop as soon as a/the up-to-date file is found, avoids re-computings of the check date (based on volatile Now!) in the loop, and demonstrates the importance of code you don't write (e.g.: Set folder = ..., If (found = false) ..).

Related

How do I use VBScript to rename files in a directory prepending the folder name to all files in the folder?

I have a large number of image files spanning nearly two decades where the subject is identified by the directory name and most of the photos themselves have a generic name however some of them have more specific names.
I am writing a script to prepend the directory name to the filename for all files in a specific directory. Well, I am trying to at least.
It has been a few years since I used VBScript and it seems I am VERY rusty.
I am facing challenges with the syntax format.
When I have Option Explicit (on line 6) it gives an error of Line 6, Char 1, Error: Expected Statement, Code: 800A0400 (In my shared code it would be line 7 because of the added Beginning of File line)
If I comment that out, I get an error on the import statements instead of Line 3, char 1, Error: Type mismatch: 'Imports', Code: 800A000D (In my shared code, it would be line 4 because of the added Beginning of File line)
I have spent a few hours googling for possible causes but to no avail and so I am turning to the community for help with getting the formatting of this script set correctly.
Any comments on a better script approach for accomplishing this task would be appreciated as well.
I am going to put in the entire code for the file because I do not know what part of it will be the relevant aspect.
In the code, it is currently set to only create a message box for each file as a test measure to ensure the variables have the values I think they have.
The commented out code for renaming the file is the truly intended purpose.
I am stuck on the proper formatting of the first part of the file however.
In general, I am executing this from the command line using: cscript.exe c:\MyTools\addDir2FileName.vbs
I launched it through windows explorer to get the more specific error codes with line numbers though.
I added the Beginning of File and End of File comments just for the purpose of clarity in this post.
' ####### Beginning of File
' Renames all files in a directory prepending the directory name to the file name
Imports System
Imports System.IO
Option Explicit
Dim WshShell, strOldFull, strNewFull, strFullPath, strCurDir
Dim strCurrentName, strNewName, strMessage, dir, fileObj, fs, fo
' Get the current directory
Set WshShell = CreateObject("WScript.Shell")
strFullPath = WshShell.CurrentDirectory
'Get folder properties to get just the name without path
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set fo=fs.GetFolder(strFullPath)
strCurDir = fo.Name
'Iterate through the directory
set dir = DirectoryInfo(strFullPath)
For Each fileObj In dir.GetFiles()
strCurrentName = fileObj.Name
strNewName = strCurDir & " - " & strCurrentName
' For testing purposes to make sure everything is as expected
' Creates a message box for each file instead of actually renaming it
strMessage = "Old Name: " & strCurrentName & chr(13) & chr(10) & "New Name: " & strNewName
MsgBox strMessage
' Renaming the file
' strOldFull = fs.BuildPath(CurrentDirectory, strCurrentName)
' strNewFull = fs.BuildPath(CurrentDirectory, strNewName)
' My.Computer.FileSystem.RenameFile(strOldFull, strNewFull)
Next
WshShell = Nothing
fo = Nothing
fs = Nothing
' ### End of File
The expectation is that a file "C:\Pictures\Trip to Nice\DCM001.jpg" will get renamed to "C:\Pictures\Trip to Nice\Trip to Nice - DCM001.jpg" and that all files in the directory that the script is run in will be similarly renamed.
Well, to be more precise, the output as currently formatted will produce a message box that says "Old Name: C:\Pictures\Trip to Nice\DCM001.jpg New Name: C:\Pictures\Trip to Nice\Trip to Nice - DCM001.jpg" and that a message box will be produced for all files in the directory. Yes, I will only run message box version in a test directory with 3 files. I would hate to get 50,000 message boxes, lol.
There is no output at current because of the formatting issues with either the Import Statement or the Option Explicit, or perhaps some other syntax piece I am missing or have wrong.
Thank you for your time and any help that anyone is able to provide. This is the first time I am posting to the community but I have long appreciated the answers provided. Usually, I can find my questions already answered, but I am stumped on this one...
Okay, through a lot of trial and error, I figured out a method to complete the task where I did not use System and so avoided the error that I was receiving before.
I thought to post the final script, in case anyone was interested.
' Renames all files in a directory prepending the directory name to the file name
Option Explicit
Dim WshShell, strOldFull, strFullPath, strCurDir, lastSlash
Dim strCurrentName, strNewName, strMessage, fileObj, fileSpec, fs, fo, ff
' Get the current directory
Set WshShell = CreateObject("WScript.Shell")
strFullPath = WshShell.CurrentDirectory
'Get folder object
Set fs = CreateObject("Scripting.FileSystemObject")
Set fo = fs.GetFolder(strFullPath)
set ff = fo.Files
'Get just the folder name
lastSlash = inStrRev(strFullPath, "\")
strCurDir = right(strFullPath, len(strFullPath) - lastSlash )
'Iterate through the directory
For Each fileObj in ff
strCurrentName = fileObj.Name
strNewName = strCurDir & " - " & strCurrentName
' For testing purposes to make sure everything is as expected
' Creates a message box for each file instead of actually renaming it
' strMessage = "Old Name: " & strCurrentName & chr(13) & chr(10) & "New Name: " & strNewName
' MsgBox strMessage
' Renaming the file
strOldFull = strFullPath & "\" & strCurrentName
set fileSpec = fs.GetFile(strOldFull)
fileSpec.Name = strNewName
Next
' Declare variables
Dim objFSO, objParentFolder, objFolder, objFile
' Set the parent directory to be processed
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objParentFolder = objFSO.GetFolder("C:\path\to\parent\directory")
' Function to process the subfolders
Sub ProcessSubFolders(folder)
' Loop through all files in the folder
For Each objFile In folder.Files
' Get the current file name
strFileName = objFile.Name
' Get the folder name
strFolderName = folder.Name
' Build the new file name
strNewFileName = strFolderName & "_" & strFileName
' Rename the file
objFile.Name = strNewFileName
Next
' Loop through all subfolders
For Each objFolder In folder.SubFolders
' Recursively call the function for the subfolder
ProcessSubFolders(objFolder)
Next
End Sub
' Call the function to process the top-level folder
ProcessSubFolders(objParentFolder)
' Clean up
Set objFile = Nothing
Set objParentFolder = Nothing
Set objFSO = Nothing

Applescript copy files to specific folders

I want to copy files to specific folders. The folder names and the file names have the first 14 characters in common.
This is my folder structure:
The Source File Structure:
Proxy
RED_A001_0101R7 (the last 6 digits are random)
A001_C001_0101RN_001_Proxy.mp4 (video file to be copied)
A001_C002_0101D5_001_Proxy.mp4 (video file to be copied)
...
RED_A001_0525A1
RED_A002_010107
...
The Destination File Structure:
FullRes
RED_A001_0101R7
A001_C001_0101RN.RDC (Folder in which the correct _Proxy file should be copied in)
A001_C002_0101D5.RDC (Folder in which the correct _Proxy file should be copied in)
...
RED_A001_0525A1
RED_A002_010107
...
As you can see unfortunately sometimes two folders begin with the same folder name (but are distinguished by the random digits that follow)
I managed to put together the following script:
set ProxyFolder to (choose folder with prompt "Choose the Source Folder")
set FullresFolder to (choose folder with prompt "Choose the Destination Folder")
tell application "System Events"
set folderList to name of folders of FullresFolder
set fileList to name of files of ProxyFolder
end tell
repeat with i from 1 to (count folderList)
set folderName to item i of folderList
set beginFolderName to text items 1 thru 14 of folderName
set filesToMove to {}
repeat with j from 1 to (count fileList)
set filename to item j of fileList
if filename begins with beginFolderName then
set end of filesToMove to alias ((ProxyFolder as string) & filename)
end if
end repeat
tell application "Finder"
duplicate filesToMove to alias ((FullresFolder as string) & folderName & ":")
end tell
end repeat
The script works - but right now I have to choose my source and destination folder for every folder A001, A002 etc. It would be more convenient to be able to choose the top-level folders as source (Folder Proxy) and destination (Folder FullRes). How can I do that?
Thats it!!
I edited my original script and it works as well, but yours is way more elegant and probably faster. Thank you very much!
Here my version:
set topLevelProxyFolder to (choose folder with prompt "Choose the PROXY Folder")
set topLevelFullresFolder to (choose folder with prompt "Choose the FULL RES Folder")
tell application "System Events"
set folderList to name of folders of topLevelFullresFolder
set proxyFolderList to name of folders of topLevelProxyFolder
end tell
set allFilesList to {}
repeat with thisProxyFolder from 1 to (count proxyFolderList)
set thisProxyFolderName to item thisProxyFolder of proxyFolderList
set thisSubProxyFolder to alias ((topLevelProxyFolder as string) & thisProxyFolderName)
tell application "System Events"
set thisFileList to name of files of thisSubProxyFolder
end tell
set allFilesList to allFilesList & thisFileList
end repeat
repeat with thisFolder from 1 to (count folderList)
set thisFolderName to item thisFolder of folderList
set thisSubFolder to alias ((topLevelFullresFolder as string) & thisFolderName)
tell application "System Events"
set subFolderList to name of folders of thisSubFolder
end tell
repeat with i from 1 to (count subFolderList)
set thisSubFolderName to item i of subFolderList
set beginSubFolderName to text items 1 thru ((get offset of "." in thisSubFolderName) - 1) of thisSubFolderName
set filesToMove to {}
repeat with j from 1 to (count allFilesList)
set fileName to item j of allFilesList
if fileName begins with beginSubFolderName then
set end of filesToMove to alias ((topLevelProxyFolder as string) & thisFolderName & ":" & fileName)
end if
end repeat
tell application "Finder"
duplicate filesToMove to alias ((topLevelFullresFolder as string) & thisFolderName & ":" & thisSubFolderName & ":")
end tell
end repeat
end repeat

2 level file loop with variable

I am new to VBS and I am trying to do something I am not sure how.
First level:
I have a set of varible names(strVar()) that I want to use them to 1 check to see if the folder exsists and then if they do not exsits create a folder
strVar(0) = "AA
strVar(1) = "AB"
strVar(2) = "AK"
strRootFolder = "C:\IN\ED\Dat\" & strVar
strSourceFolder = X:\\IN\ED\Dat\" & strVar
Once the File structure is there as shown in strRootFolder I need to put another folder in each of those folders called "CAL"
So my file structure for example would be-
"C:\IN\ED\Dat\AA\Cal\"
"C:\IN\ED\Dat\AB\Cal\"
"C:\IN\ED\Dat\AK\Cal\"
Second level:
- There will be a multiple files(number unknown) that will have the same fileType as the Variable in my list. So it would look like (C:\IN\ED\Dat\AA\Cal\testfile.AA). I need to be able to go through Each file in each folder and compare the last date modified to the strSourceFolders last date modified and if source is newer replace the rootfolders file.
So
If not strRootFolder & "*.AA" = strSourceFolder & "*.AA" Then
Copyfile strsourcefolder ---> strRootFolder

Need a bat file or vbs that will create shortcuts for all files in a folder

I am looking or a way that end users can have shortcuts to frequently used files populated on their desktop. The files are in a specific folder in a mapped drive that is asigned to each user (L:\Desktop) and I would like to have a script or bat file that when run would create a shortcut for each file in this folder on the desktop.
Ideally this would be included or added to a bat file I have that takes files saved to the desktop and dumps them into the server share for security.
Use the Docs. Steal the sample code for CreateShortcut (first Google hit for "vbscript shortcut"):
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
and for the Files collection (first Google hit for "vbscript files", "vbscript files collection)):
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
'get the folder by giving its path
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
study the articles carefully, lookup terms unknown to you, and weave the code into one script.

How to call a SQL script from within another SQL script?

i want to call a series of .sql scripts to create the initial database structure
script1.sql
script2.sql
etc.
is there any way of doing this without sqlcmd or stored procedures or any other kind of code that is not sql ?
just inside a .sql file.
you could try this:
exec master..xp_cmdshell 'osql -E -ix:\path\filename.sql'
osql must be in the path, the full filename must be known, and logins have to be set up correctly (options -E or -U)
Sure. Just create a little app that pulls in all the .sql files you want and executes them. Do it in VB.NET as follows:
Sub ExecuteSqlScript(FilePath As String)
Dim Script As String
Dim FileNumber As Integer
Dim Delimiter As String
Dim aSubscript() As String
Dim Subscript As String
Dim i As Long
Delimiter = ";"
FileNumber = FreeFile
Script = String(FileLen(FilePath), vbNullChar)
' Grab the scripts inside the file
Open FilePath For Binary As #FileNumber
Get #FileNumber, , Script
Close #FileNumber
' Put the scripts into an array
aSubscript = Split(Script, Delimiter)
' Run each script in the array
For i = 0 To UBound(aSubscript) - 1
aSubscript(i) = Trim(aSubscript(i))
Subscript = aSubscript(i)
CurrentProject.Connection.Execute Subscript
Next i
End Sub
Example from: http://snipplr.com/view/3879/run-sql-script-from-external-file/
There's no reason to exclude stored procedures. You don't need to include "any other kind of code that is not sql", plus
EXEC someothersp
which will be required (or its equivalent) in any other solution.
What's your reason for excluding them? I would sure think it beats writing code in yet another language.

Resources