.vbs script gets stuck when run as Scheduled Task - vbscript

I have a VBS file that was provided to me, and I have made small changes to. The script runs fine when I double click it, however when it's set to run as a scheduled task, the status remains as "Running"; usually the task is completed in a matter of seconds.
Can anyone suggest why this may be?
Thanks
wscript.echo "VBScript Create_TaxiCheck_File"
Const InputFile = "C:\TaxiCheckLive\TaxiCheck_Data.txt"
Const OutputFile = "C:\TaxiCheckLive\TaxiCheck_Formatted.txt"
Const CSVFile = "C:\TaxiCheckLive\ChelmsfordExtract.csv"
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Dim fso
Dim I
Dim IF1
Dim OF1
Dim InputLine
Dim Outputline
Dim comma
Set fso = CreateObject("Scripting.FileSystemObject")
'check input file exists
if (fso.fileexists(InputFile)) then
wscript.echo "Input file exists: " & InputFile
'Write to log file (File exists)
Set LogFile = fso.OpenTextFile("LogFile.txt", ForAppending)
LogFile.WriteLine DateInfo & Now & " - OK, Input file exists"
LogFile.close
Else
'Write to log file (File does not exist)
Set LogFile = fso.OpenTextFile("LogFile.txt", ForAppending)
LogFile.WriteLine DateInfo & Now & " - Error, input file does not exist, database export has not run!" & VbCrLf
LogFile.close
wscript.Quit(9)
end if
'if exists then delete output file
if (fso.fileexists(OutputFile)) then
wscript.echo "Deleting file: " & OutputFile
Set OF1 = fso.GetFile(OutputFile)
OF1.Delete
end if
'create output file
wscript.echo "Creating output file: " & OutputFile
Set OF1 = fso.CreateTextFile(OutputFile, True)
OF1.Close
'if exists then delete CSV file
if (fso.fileexists(CSVFile)) then
wscript.echo "Deleting file: " & CSVFile
Set OF1 = fso.GetFile(CSVFile)
OF1.Delete
end if
'create formated output file.
wscript.echo "Create formated output file."
Set IF1 = fso.OpenTextFile(InputFile, ForReading)
Set OF1 = fso.OpenTextFile(OutputFile, ForWriting)
Outputline = "MODE,VEH_REG_NO_NO_SPACES,VEH_MAKE,VEH_MODEL,VEH_COLOUR,LIC_NUMBER"
OF1.WriteLine Outputline
Outputline = "D,*"
OF1.WriteLine Outputline
Outputline = ""
Do While Not IF1.AtEndOfStream
InputLine = IF1.ReadLine
Outputline = "I," + InputLine
OF1.WriteLine Outputline
Outputline = ""
Loop
'copy output file to CSV file
fso.CopyFile OutputFile, CSVFile
'close input and output files
IF1.Close
OF1.Close
'delete input and output files
Set OF2 = fso.GetFile(InputFile)
OF2.Delete
Set OF3 = fso.GetFile(OutputFile)
OF3.Delete
'ftp file to firmstep ftp site
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run("%windir%\system32\ftp.exe -s:C:\TaxiCheckLive\ftpcommands.txt")
wscript.echo "VBScript Create_TaxiCheck_File Ended Successfully"
'Write to log file (complete)
Set LogFile = fso.OpenTextFile("LogFile.txt", ForAppending)
LogFile.WriteLine DateInfo & Now & " - Script completed running" & VbCrLf
LogFile.close
wscript.Quit(1)

wscript.echo in an unattended VBS can cause issues, as the script will be waiting for someone to hit the 'ok' button. Remove them or comment them out.

I had a similar problem.
My scheduled task was running under a specific user. Using the component services snap in for MMC I needed to give the user 'Launch and activation' permissions. Once this was done, the scheduled task ran correctly.
The line 'CreateObject("Scripting.FileSystemObject")' will require these permissions I believe.

Related

VBS/BAT - Show Progress of Script Execution

I have roughly 8 scripts that need to be executed, and some of the scripts may sometimes take a while to complete the execution and all you get to see is the message box at the end of the script that says completed once everything is done..
I am looking for a way to show some form of progress/progress bar while the scripts execute, if this is even possible?
I read somewhere that it is easier/possible to show a progress bar in command line, but all my code are in vbscript files..
Currently, I have a bat file that calls and executes my scripts for me.
Here is an example of just one of my scripts that takes a while - This code looks in a specific path directory for the 3 latest csv files and then copies them to a new location:
Option Explicit
Dim FolderToCheck, FolderDestination, FileExt, mostRecent, noFiles, fso, fileList, file, filecounter, oShell, strHomeFolder
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
'Variables -----
folderToCheck = strHomeFolder & "X:\Data\Terminations\Daily_Terminations" ' Folder Source to check for recent files to copy FROM
folderDestination = strHomeFolder & "X:\Test\Terminations" ' Destination Folder where to copy files TO
fileExt = "csv" ' Extension we are searching for
mostRecent = 3 ' Most Recent number of files to copy
' --------------
PreProcessing() ' Retrieve Command Line Parameters
' Display what we are intending on doing
'wscript.echo "Checking Source: " & FolderToCheck & "For Files of type: " & FileExt
'wscript.echo "Copying most recent file(s) to: " & FolderDestination & "."
noFiles = TRUE
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileList = CreateObject("ADOR.Recordset")
fileList.Fields.append "name", 200, 255
fileList.Fields.Append "date", 7
fileList.Open
If fso.FolderExists(FolderToCheck) Then
For Each file In fso.GetFolder(FolderToCheck).files
If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
fileList.AddNew
fileList("name").Value = File.Path
fileList("date").Value = File.DateLastModified
fileList.Update
If noFiles Then noFiles = FALSE
End If
Next
If Not(noFiles) Then
'wscript.echo fileList.recordCount & " File(s) found. Sorting and copying last " & mostRecent &"..."
fileList.Sort = "date DESC"
If Not(fileList.EOF) Then
fileList.MoveFirst
If fileList.recordCount < mostRecent Then
wscript.echo "WARNING: " & mostRecent &" file(s) specified but only " & fileList.recordcount & " file(s) match criteria. Adjusted to " & fileList.RecordCount & "."
mostRecent = fileList.recordcount
End If
fileCounter = 0
Do Until fileList.EOF Or fileCounter => mostRecent
If Not(fso.FolderExists(folderDestination)) Then
wscript.echo "Destination Folder did not exist. Creating..."
fso.createFolder folderDestination
End If
fso.copyfile fileList("name"), folderDestination & "\", True
'wscript.echo fileList("date").value & vbTab & fileList("name")
fileList.moveNext
fileCounter = fileCounter + 1
Loop
wscript.echo "Files Seccuessfully Copied"
Else
wscript.echo "An unexpected error has occured."
End If
Else
wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
End If
Else
wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If
fileList.Close
Function PreProcessing
Dim source, destination, ext, recent
' Initialize some variables
Set source = Nothing
Set destination = Nothing
Set ext = Nothing
Set recent = Nothing
source = wscript.arguments.Named.Item("source")
destination = wscript.arguments.Named.Item("destination")
ext = wscript.arguments.Named.Item("ext")
recent = wscript.arguments.Named.Item("recent")
If source <> "" Then FolderToCheck = source
If destination <> "" Then FolderDestination = destination
If ext <> "" Then FileExt = ext
If recent <> "" Then mostRecent = int(recent)
End Function

Uploading folder content to FTP with VBScript gives dialog box to overwrite existing file

This is one of the first times I am using VBScript to create a task I want to run in a program called Qlikview.
What I want to do is upload all the content of one local folder to an FTP folder but when a file is already on that FTP folder it just needs to "Overwrite All" so do "Yes to All" automatically
Here is my code:
Function FTPUpload(FTPHost, FTPUser, FTPPass, FTPPath)
Set oShell = CreateObject("Shell.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
'Copy Options: 16 = Yes to All
Const copyType = 16
strFTP = "ftp://" & FTPUser & ":" & FTPPass & "#" & FTPHost
Set objFTP = oShell.NameSpace(strFTP)
'Upload all files in folder
If objFSO.FolderExists(FTPPath) Then
'Code below can be used to upload entire folder
Set objFolder = oShell.NameSpace(FTPPath)
Wscript.Echo "Uploading folder " & FTPPath & " to " & strFTP
objFTP.CopyHere objFolder.Items, copyType
End If
'If Err.Number <> 0 Then
' Wscript.Echo "Error: " & Err.Description
'End If
On Error Goto 0
End function
I use objFTP.CopyHere objFolder.Items, copyType to copy the content and copyType = 16 I found this on the internet Here where 16 stands for "Yes to All" when a dialog appears.
The problem is when I run this code, it uploads to the FTP but when a file exists I keep getting the overwrite dialog. What could be the problem?

Copy 1 latest extension MDB file from a source folder to destination folder for WIN 2000

I have a script whereby this will copy 2 files(ext: txt) from a source folder to destination folder based on the latest date file. I have tested with WIN 7 and Vista and it is working fine. I get the output that i wanted. When i tested with WIN 2000 with different file extension MDB file and folder path, i could not get the output. Here, i have edit to only copy 1 latest file. Please check the script below and help me :-(
Option Explicit
Dim FolderToCheck, FolderDestination, FileExt, mostRecent, noFiles, fso, fileList, file, filecounter, oShell, strHomeFolder
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
'Variables -----
folderToCheck = strHomeFolder & "C:\Mms2\MDB"' Folder Source to check for recent files to copy FROM
folderDestination = strHomeFolder & "C:\Documents and Settings\Mms\Desktop\Test"'Destination Folder where to copy files TO
fileExt = "MDB" ' Extension we are searching for
mostRecent = 1 ' Most Recent number of files to copy
' --------------
'PreProcessing() ' Retrieve Command Line Parameters
' Display what we are intending on doing
' wscript.echo "Checking Source: " & FolderToCheck
' wscript.echo "For Files of type: " & FileExt
' wscript.echo "Copying most recent "& mostRecent &" file(s) to: " & FolderDestination & "."
' wscript.echo
noFiles = TRUE
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileList = CreateObject("ADOR.Recordset")
fileList.Fields.append "name", 200, 255
fileList.Fields.Append "date", 7
fileList.Open
If fso.FolderExists(FolderToCheck) Then
For Each file In fso.GetFolder(FolderToCheck).files
If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
fileList.AddNew
fileList("name").Value = File.Path
fileList("date").Value = File.DateLastModified
fileList.Update
If noFiles Then noFiles = FALSE
End If
Next
If Not(noFiles) Then
' wscript.echo fileList.recordCount & " File(s) found. Sorting and copying last " & mostRecent &"..."
fileList.Sort = "date DESC"
If Not(fileList.EOF) Then
fileList.MoveFirst
If fileList.recordCount < mostRecent Then
' wscript.echo "WARNING: " & mostRecent &" file(s) specified but only " & fileList.recordcount & " file(s) match criteria. Adjusted to " & fileList.RecordCount & "."
mostRecent = fileList.recordcount
End If
fileCounter = 0
Do Until fileList.EOF Or fileCounter => mostRecent
If Not(fso.FolderExists(folderDestination)) Then
' wscript.echo "Destination Folder did not exist. Creating..."
fso.createFolder folderDestination
End If
fso.copyfile fileList("name"), folderDestination & "\", True
' wscript.echo fileList("date").value & vbTab & fileList("name")
fileList.moveNext
fileCounter = fileCounter + 1
Loop
Else
' wscript.echo "An unexpected error has occured."
End If
Else
' wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
End If
Else
' wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If
fileList.Close
Function PreProcessing
Dim source, destination, ext, recent
' Initialize some variables
Set source = Nothing
Set destination = Nothing
Set ext = Nothing
Set recent = Nothing
'Get Command Line arguments
' <scriptname>.vbs /Source:"C:\somepath\somefolder" /Destination:"C:\someotherpath\somefolder" /ext:MDB /recent:1
source = wscript.arguments.Named.Item("source")
destination = wscript.arguments.Named.Item("destination")
ext = wscript.arguments.Named.Item("ext")
recent = wscript.arguments.Named.Item("recent")
If source <> "" Then FolderToCheck = source
If destination <> "" Then FolderDestination = destination
If ext <> "" Then FileExt = ext
If recent <> "" Then mostRecent = int(recent)
End Function
you'll need to change a few things:
Remove these lines - they're not required any more:
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
Update these lines:
'Variables -----
folderToCheck = "C:\Mms2\MDB" ' Folder Source to check for recent files to copy FROM
folderDestination = "C:\Documents and Settings\Mms\Desktop\Test" 'Destination Folder where to copy files TO

VBscript to zip log files with 7zip

Would like someone to take a look at my script and tell me where I am messing up.
It is a script to zip log files and then I would like to move them into a new folder that is going to be shared over a network. Right now I am just trying to get the part where it zips up the files using 7zip correctly.
I am very new to VB (like 2 days) so having some syntax problems I think.
Script is found below, thank you in advance for all advice and help
Option Explicit
WScript.Echo "Press to start zipping log files."
Dim objFile, objPath, objFolder, Command, PathLogs, RetVal
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objShell: Set objShell = CreateObject("WScript.Shell")
PathLogs = "C:\Testscripts\testfolder\" 'This path just has some test logs
' Loop through the logs and zip and move each file (if required, you could just move files with an '.log' extension)
Set objPath = objFSO.GetFolder(PathLogs)
For Each objFile In objPath.Files
If (LCase(objfso.GetExtensionName(objFile)) = "log") Then
Wscript.Echo objFile.Name
' zip and move files
'Command = """C:\Program Files\7-zip\7z.exe"" -m -ex """ & PathLogs & \objFile.Name objfso.GetBaseName(objFile) & "*.zip"" """ & PathLogs & objFile.Name & """"
Command = ""C:\Program Files\7-zip\7z.exe"" a -m -ex " & PathLogs & "" & objFile.Name & ".zip " & PathLogs & "" & objFile.Name & "
WScript.Echo "Command: " & Command
RetVal = objShell.Run(Command,0,true)
End If
Next
WScript.Echo "Zip Successful."
You have your quotes wrong. To use a quote inside a string, you have to duplicate the quote.
Command = """C:\Program Files\7-zip\7z.exe"" a -m -ex " _ 'this is the first part of the string
& PathLogs & objFile.Name & ".zip " & PathLogs & objFile.Name
If your Logfile or PathLogs can contain spaces they must be quoted as well.

Why do we need generate a temporary file when remote uploading to FTP?

I am so confused with this, I am trying to upload data to FTP through VBS script and it works fine for a single file file but doesn't upload multiple files when I add the script inside a loop.
Also , why do we need to generate a temporary file when remote uploading to FTP,
I mean to say this,
this is the script I am using,
Dim fso, folder, files, strPath
Set fso = CreateObject("Scripting.FileSystemObject")
strPath = "E:/Test"
Set folder = fso.GetFolder(strPath)
Set files = folder.Files
Const hostname = "ftp.domain.com"
Const port = 21
Const username = "username"
Const password = "password"
Const remoteDir = "/"
Const useDefaultsExclusively = True
Const skipConfirmation = True
For each item In files
If InStr(1, item.Name, "txt") <> 0 Then
defaultFile = item.Name
localFile = fso.getFileName(defaultFile)
localDir = fso.getParentFolderName(defaultFile)
Set shell = CreateObject("WScript.Shell")
tempDir = shell.ExpandEnvironmentStrings("%TEMP%")
' temporary script file supplied to Windows FTP client
scriptFile = tempDir & "\" & fso.GetTempName
' temporary file to store standard output from Windows FTP client
outputFile = tempDir & "\" & fso.GetTempName
'input script
script = script & "lcd " & """" & localDir & """" & vbCRLF
script = script & "open " & hostname & " " & port & vbCRLF
script = script & "user " & username & vbCRLF
script = script & password & vbCRLF
script = script & "cd " & """" & remoteDir & """" & vbCRLF
script = script & "binary" & vbCRLF
script = script & "prompt n" & vbCRLF
script = script & "put " & """" & localFile & """" & vbCRLF
script = script & "quit" & vbCRLF
Set textFile = fso.CreateTextFile(scriptFile, True)
textFile.WriteLine(script)
' bWaitOnReturn set to TRUE - indicating script should wait for the program
' to finish executing before continuing to the next statement
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, TRUE
Wscript.Sleep 10
' open standard output temp file read only, failing if not present
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2)
results = textFile.ReadAll
textFile.Close
End If
Next
fso.DeleteFile(scriptFile)
fso.DeleteFile(outputFile)
Why do we creating a Temporary file with this code, :S
Set shell = CreateObject("WScript.Shell")
tempDir = shell.ExpandEnvironmentStrings("%TEMP%")
' temporary script file supplied to Windows FTP client
scriptFile = tempDir & "\" & fso.GetTempName
' temporary file to store standard output from Windows FTP client
outputFile = tempDir & "\" & fso.GetTempName
Set textFile = fso.CreateTextFile(scriptFile, True)
textFile.WriteLine(script)
' bWaitOnReturn set to TRUE - indicating script should wait for the program
' to finish executing before continuing to the next statement
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, TRUE
Wscript.Sleep 10
' open standard output temp file read only, failing if not present
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2)
results = textFile.ReadAll
textFile.Close
Although I am looping through the script , it must upload every txt file inside current directory but it uploads only the first one, why is it so ?
When I print the current file i.e
MsgBox defaultfile
it display the name of each txt file inside the current folder but uploads first file only.
There is no native method of live automation for FTP. This is actually a scripting workaround. Your script is creating a text file with FTP instructions. Then, it launches FTP from the command line using the -s switch. That -s switch allows you to provide a text file containing session commands for FTP.exe to execute before closing. So while your script isn't actually automating the FTP program directly, it simulates automation by running FTP in "unattended mode". You can get a better understanding by opening a command prompt and typing ftp /?.
[EDIT]
I apologize, I missed your second question. Your script is only uploading the first file because it loops around the CreateTextFile method. This method is failing after the first attempt because the file already exists. What you really ought to do is loop around adding your files to the temporary file and then execute FTP only once. Your web server will appreciate the break as well.
Dim fso, folder, files, strPath
Set fso = CreateObject("Scripting.FileSystemObject")
strPath = "E:/Test"
Set folder = fso.GetFolder(strPath)
Set files = folder.Files
Const hostname = "ftp.domain.com"
Const port = 21
Const username = "username"
Const password = "password"
Const remoteDir = "/"
Const useDefaultsExclusively = True
Const skipConfirmation = True
tempDir = shell.ExpandEnvironmentStrings("%TEMP%")
' temporary script file supplied to Windows FTP client
scriptFile = tempDir & "\" & fso.GetTempName
' temporary file to store standard output from Windows FTP client
outputFile = tempDir & "\" & fso.GetTempName
Set textFile = fso.CreateTextFile(scriptFile, True)
'input script
textFile.WriteLine("open " & hostname & " " & port)
textFile.WriteLine("user " & username)
textFile.WriteLine(password)
textFile.WriteLine("cd " & Chr(34) & remoteDir & Chr(34))
textFile.WriteLine("binary")
textFile.WriteLine("prompt n")
For Each item In files
If InStr(1, item.Name, "txt") <> 0 Then
textFile.WriteLine("put " & Chr(34) & item.Path & "\" & item.Name & Chr(34))
End If
Next
textFile.WriteLine("quit")
textFile.Close
Set shell = CreateObject("WScript.Shell")
' bWaitOnReturn set to TRUE - indicating script should wait for the program
' to finish executing before continuing to the next statement
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, True
WScript.Sleep 10
' open standard output temp file read only, failing if not present
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2)
results = textFile.ReadAll
textFile.Close
fso.DeleteFile(scriptFile)
fso.DeleteFile(outputFile)

Resources