print all files in folder and then remove them - vbscript

I am creating a web-based Point of Sale, and right now I am getting stuck with the VBScript.
The script should be printing all files in the selected folder, and after that I want to remove the files printed.
The selected folder will only contain PDF files that are going to be printed.
This is my current code:
TargetFolder = "C:\Users\pos\Downloads\"
If TargetFolder > "" Then
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(TargetFolder)
Set colItems = objFolder.Items
For Each objItem in colItems
objItem.InvokeVerbEx("Print")
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.GetFile(TargetFolder+objItem)
MyFile.Delete
Next
Else
Wscript.Quit
End If
All files are printed if I remove the remove file part, With the remove files it will delete all files before they get printed.
So what I want is to print the files, and remove them once they are printed.

You can detect whether printer jobs queue is empty before deleting files.
Do
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select Document from Win32_PrintJob", , 48)
WScript.Sleep(1000)
Loop While colItems.Count > 0
And then delete files in another loop.

Related

VBScript command to wait for files to be extracted before launching EXE to install program

I'm looking at having a script that decompresses a file (PDMsetup.zip) and then launch the executable that it extracts.
ZipFile="PDMsetup.zip"
ExtractTo=".\"
Set fso = CreateObject("Scripting.FileSystemObject")
sourceFile = fso.GetAbsolutePathName(ZipFile)
destFolder = fso.GetAbsolutePathName(ExtractTo)
Set objShell = CreateObject("Shell.Application")
Set FilesInZip=objShell.NameSpace(sourceFile).Items()
objShell.NameSpace(destFolder).copyHere FilesInZip, 16
Set fso = Nothing
Set objShell = Nothing
Set FilesInZip = Nothing
wscript.sleep 480000
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
strPath = strFolder & "\Startwinstall.exe"
objShell.Run strPath
I want to get rid of;
wscript.sleep 480000
and replace it with a command that tells the script wait until the extraction is done before launching startwinstall.exe
I've kept adjusting the wait time to make up for differences in PC performance with the extraction, but a command to just 'wait' until it's done would be preferential.
Delete any previous copy of the installer exe in the target folder and then wait for that file to be created. Create your objects once at the top of the script. And there's no need to set the objects to Nothing. That will happen automatically when the script ends. The edited script is below:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oWSH = CreateObject("Wscript.Shell")
Set oApp = CreateObject("Shell.Application")
MyFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
ExtractTo = ".\"
ZipFile = "PDMsetup.zip"
StartApp = ExtractTo & "Startwinstall.exe"
On Error Resume Next
oFSO.DeleteFile StartApp
On Error Goto 0
sourceFile = oFSO.GetAbsolutePathName(ZipFile)
destFolder = oFSO.GetAbsolutePathName(ExtractTo)
Set FilesInZip = oApp.NameSpace(sourceFile).Items()
oApp.NameSpace(destFolder).copyHere FilesInZip, 16
Do Until oFSO.FileExists(StartApp)
WScript.Sleep 1000
Loop
oWSH.Run StartApp
Note: I assigned a MyFolder variable, but it's not currently being used. ExtractTo = ".\" could be changed to ExtractTo = MyFolder. You could also eliminate the GetAbsolutePathName lines if you are using MyFolder with the ZipFile name. There are always many ways to do the same thing.
Note: I think the above can be done with a much briefer (probably two line) PowerShell script. Let me know if you're interested in that solution.

Change DateLastModified property of Folder to match file within

I have a number of folders, each with files inside the folder.
The structure looks something like this:
Folder.No.1
Folder_No_2
Folder No 3
and the files within are something like:
Folder.No.1\My.Movie.1.mp4
Folder.No.1\My.Movie.1.txt
Folder_No_2\My_Movie_2.mp4
Folder_No_2\My_Movie_2.jpg
Folder_No_2\My_Movie_2.txt
Folder No 3\My Movie 3.mp4
As you can see, some folders contain . in the name, some contain _ and some contain spaces.
The one consistent factor is that each folder will always contain an .mp4 file, regardless of anything else.
Therefore, how can I change the Date Modified date/time of the folder to match that of the .avi file contained within the folder? Can I do this by copying the DateLastModified from the file inside (the child) to the parent folder using VBScript?
So far I am working on something like this:
Dim objShell, objFolder, objFile
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(strDir)
Set strDir = objFile.GetFolder("C:\Temp")
For Each objFile In objFolder
If UCase(objFolder.GetExtensionName(objFile.Name)) = "MP4" Then
objFolder.Items.Item(strDir).ModifyDate = DateLastModified
WScript.Echo objFolder.Name
End If
Next
but it fails when calling from command line with: cscript CopyDateToParent.vbs
Can anyone please help to correct this to make it work?
Try my code :
StrFolder="C:\Users\admin\Desktop\" 'Your folder
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
Set objFolder = objFSO.GetFolder(StrFolder)
Set Folder = objShell.NameSpace(StrFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Name=objFile.Name
strExtension = LCase(objFSO.GetExtensionName(Name))
If strExtension = "mp4" Then
Set objFolderItem = Folder.ParseName(Name)
objFolderItem.ModifyDate = DateLastModified 'Example : "01/01/2008 8:00:00 AM"
End If
Next

Too many iterations in loop

This script collects all files in a folder and renames the files by appending the number of lines to the file name. All files are .txt files. The method (since fso.MoveFile and fso.DeleteFile are too particular, generating permissions errors) is to
create the text files,
then create a collection of the files in the folder,
then copy each file into the same folder with a new name, and
finally to delete the original file that was copied.
The script works ok, unless there are no empty text files in the collection. What happens is, the collection gets rebuilt with the new files and the script once again renames the files. I know I can prevent this by checking each file for the existence of certain repeating character strings, but I'd like to know what's happening? Why does the script rebuild the file collection and run through them again renaming each one? This continues on until I kill the process.
Another interesting factoid is, if I happen to trap an empty text file, my message is displayed and the script stops there, but has still reprocessed the first file in the collection a second time. Note that the empty file just happens to be the last one in the collection, but the first filed is once again processed.
So, by design a created text file named 'ab0.txt' gets renamed to 'ab0-15.txt' since it has 15 lines of text in it. What happens is this newly renamed file looks like 'ab0-15-15-15-15-15-15-15-15-15-15.txt'
Questions: What's going on? And is there a better and more efficient way to accomplish this objective?
Here's the code pertinent to the issue:
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFolder = fso.GetFolder(strSaveTo)
Set colFiles = oFolder.Files
' Call Sub to copy and rename
ChangeFileName colFiles
MsgBox("File renaming complete.")
' Exit code
Sub ChangeFileName(collectionSet)
Const ForReading = 1
Dim oFile
For Each oFile In collectionSet
Set LineCnt = fso.OpenTextFile(oFile, ForReading)
If oFile.Size = 0 then
'if this msg is not included, weird things happen
MsgBox("The file named " & oFile & _
" is empty.You may want to verify and manually delete it.")
'[I had some code in here to delete the empty file, but nothing worked]
Else
Do While LineCnt.AtEndOfStream <> True
LineCnt.SkipLine
Loop
lineVar = lineCnt.Line-1
strNewFile = strSaveTo & Left(oFile.name, Len(oFile.name)-4) & _
"-" & lineVar & ".txt"
fso.CopyFile oFile, strNewFile
LineCnt.Close
fso.DeleteFile oFile, True
End If
Next
End Sub
I've heard anecdotal evidence that the Files collection is "live", meaning that newly created files will be added to the collection and iterated over, but I can't find any documentation that says one way or the other. In any case, it's probably a good idea to copy the File objects in the collection to an array first before processing them:
Dim oFile
Dim fileArray()
Dim i
ReDim fileArray(collectionSet - 1)
i = 0
For Each oFile in collectionSet
Set fileArray(i) = oFile
i = i + 1
Next
For Each oFile In fileArray
' Count lines and rename
Next
It seems that collectionSet is the collection of files in the folder that you are trying to modify. The problem is that with each pass through the for-each loop you are adding files to this folder, some of which are fed back into the loop. What you need to do is the find a way to take a snapshot of the folder before you try to iterate over it. The way to do this would be to replace the folder collectionSet by a collection of strings which are the names of the files before you iterate over it, and modify your code to open the files by their name (instead of via a file object). That way the collection won't be expanding while you iterate over it.
You should create your vars in the scope they are used (e.g. your
file/folder objects are used in the sub.
Always explicit(ly) declare your vars.
You don't need to copy the file and rename it then do the delete.
Just rename it with the FileObject.Name property.
Here is an example:
Option Explicit 'always declare your vars!
Dim strFolder: strFolder = "c:\temp\Rename Test"
Dim strExtension: strExtension = "txt"
' Call Sub to rename the files in the folder
ChangeFileName strFolder, strExtension
Sub ChangeFileName(strFolder, strExtension)
Const ForReading = 1
Dim FSO: set FSO = CreateObject("Scripting.FileSystemObject")
Dim objFolder: set objFolder = FSO.GetFolder(strFolder)
Dim colFiles: set colFiles = objFolder.Files
Dim objFile
Dim intCount
Dim strFileName
Dim objTextStream
For Each objFile In colFiles
msgbox "File: " & objfile.path & vbcrlf & FSO.GetExtensionName(objFile.path)
if UCase(FSO.GetExtensionName(objFile.Path)) = UCase(strExtension) and _
objFile.Size > 0 then
'set LineCnt = FSO.OpenTextFile(objFile, ForReading)
set objTextStream = objFile.OpenAsTextStream(ForReading,-2)
intCount = 0
strFileName = objFile.Name
Do While objTextStream.AtEndOfStream <> True
intCount = intCount + 1
objTextStream.ReadLine
Loop
objTextStream.Close
objFile.Name = FSO.GetBaseName(objFile.Path) & "-" & _
intCount & "." & FSO.GetExtensionName(objFile.Path)
end if
Next
End Sub

How to Copy a file that was read from a list

Hello guys I have an issue or issues with my code above
I'm trying to get "sExtension" to be search in a different folder other that the one I'm using to save my script since this script will be use as a Startup Script on many computers
(It works only if I run the script in the same folder "sExtension", "ExtAssign.txt" and sComputername are otherwise it wont find the path)
This is what it should do
Read a file called "ExtAssign.txt" (There is a full list of computer names in that file) and if it find the computer name on that file then it should copy a file with the with the extension number assigned to that computer name from a file server to "C:\" Drive
For this example I'm trying to do this locally, If I can make it then I'll try it from my File Server
Set objFSO = CreateObject("Scripting.FileSystemObject")
set oFso = CreateObject("Scripting.FileSystemObject")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
set oShell = WScript.CreateObject("WScript.Shell")
set oShellEnv = oShell.Environment("Process")
Set folder = Fso.GetFolder("C:\Users\XXXXX\Desktop\Test\Extensions\")
Set wshshell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set ObjEnv = WshShell.Environment("Process")
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Scomputername = ObjEnv("COMPUTERNAME")
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objWShell = wScript.createObject("WScript.Shell")
Dim strFile
'File to scan
strFile = "C:\Users\XXXXX\Desktop\Test\Extensions\Extassign\ExtAssign.txt"
Dim strPattern
'Look for computer name in file
strPattern = scomputername
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
Dim strLine
'Read each line and store it in strLine
strLine = objFile.ReadLine
'If the line matches the computer name, save the line to ExtArray
If InStr(strLine,strPattern)>0 Then
Dim ExtArray
'Split the line and separate the extension
ExtArray = Split(strLine,"|", -1, 1)
Dim sExtension
'Save the extension to sExtension
sExtension=ExtArray(1)
End If
Loop
'If the sExtension is empty, computer was not found, send message and terminate script.
If sExtension="" Then
WScript.Echo "ERROR: Computer "& scomputername &" not found in Extension Assignment List, so no extension has been set. Avaya will not be launched. Please contact your IT department for assistance."
Else
'If the sExtension contains a number, Copy that file to C:\ and rename it to Config.xml
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
End If
at the end it if it finds the file sExtension it will rename it to Config.xml but it wont do it unless I run the script in the same folder sExtension and sComputername.
I get File not found error
Thank you in advance and Happy new year!
The culprit is most likely this line:
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
There is a trailing space after the last backslash in the path, so you're creating a path
C:\Users\XXXXX\Desktop\Test\Extensions\ 12345
^
when you actually want a path
C:\Users\XXXXX\Desktop\Test\Extensions\12345
On a more general note: why are you creating 7(!) FileSystemObject instances (replacing one of them three times on top of that)? And 3(!) WScript.Shell instances? You don't even use most of them, not to mention that you don't need the Shell object in the first place. You only use it for determining the computer name, which could be done just fine using the WScript.Network object (that you don't use at all).
Also, please don't ever use comments like this:
'Read each line and store it in strLine
strLine = objFile.ReadLine
It's quite obvious that you read each line and assign it to the variable strLine. Comments shouldn't rephrase what you're doing (the code already does that, at least when you're using speaking variable and function names), but why you're doing it, i.e. what the purpose of a particular code section is.
Your code could be reduced to something as simple as this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set net = CreateObject("WScript.Network")
computername = net.ComputerName
foldername = "C:\Users\XXXXX\Desktop\Test\Extensions"
filename = fso.BuildPath(foldername, "Extassign\ExtAssign.txt")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If InStr(line, computername) > 0 Then
arr = Split(line, "|", -1, 1)
If UBound(arr) >= 1 Then extension = arr(1)
End If
Loop
f.Close
If IsEmpty(extension) Then
WScript.Echo "ERROR: Computer "& computername &" not found in ..."
Else
fso.CopyFile fso.BuildPath(foldername, extension), "C:\Config.xml", True
End If

VBScript current directory + sub directory?

I am trying to get the path of a file that is within a sub-directory of the current directory in VBScript. The following does not seem to work?
currentDirectory = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
FileToCopy = currentDirectory & "\test\user.js"
Here is the entire code:
Set oFSO = CreateObject("Scripting.FileSystemObject")
strFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
FileToCopy = oFSO.BuildPath(strFolder, "unproxy\user.js")
''# get AppdataPath
Set WshShell = CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("PROCESS")
AppdataPath = WshSysEnv("APPDATA")
FoxProfilePath = AppdataPath & "\Mozilla\Firefox\Profiles\"
'"# is firefox and user.js present?
if oFSO.FolderExists(FoxProfilePath) AND oFSO.FileExists(FileToCopy) Then
''# copy user.js in all profilefolders to get around those random profile names =)
For Each ProfileFolder In oFSO.GetFolder(FoxProfilePath).Subfolders
oFSO.GetFile(FileToCopy).Copy ProfileFolder & "\" & FileToCopy, True
Next
End If
'"# clean up
Set oFSO = Nothing
Set WshShell = Nothing
Set WshSysEnv = Nothing
I recommend using FileSystemObject when dealing with file paths:
Set oFSO = CreateObject("Scripting.FileSystemObject")
strFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
FileToCopy = oFSO.BuildPath(strFolder, "test\user.js")
Edit: The problem is in this line of your script:
oFSO.GetFile(FileToCopy).Copy ProfileFolder & "\" & FileToCopy, True
Since FileToCopy contains a full file name, when you concatenate it with ProfileFolder you get an invalid file name, like this:
C:\Documents and Settings\username\Application Data\Mozilla\Firefox\Profiles\mlreq6kv.default\D:\unproxy\user.js
Change this line to the one below, and your script should work fine. (Note: the trailing path separator at the end of ProfileFolder is required to indicate that the profile folder, e.g. mlreq6kv.default, is indeed a folder and not a file.)
oFSO.GetFile(FileToCopy).Copy ProfileFolder & "\", True
You can get the current directory with :
Set WSHShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory

Resources