vbscript to copy file from an external disk - windows

A friend and I started building a VBScript that with the goal to copy any opened files/some specific format of docs (like pdf, pptx) when we insert an external hard disk or USB on the computer. We got our script as far as only copying all docs of a specific format from one the external hard disk/USB to my computer, but we must manually execute the script after inserting the external hard disk/USB.
What we would like the script to do:
Start automatically when an external hard disk/USB is inserted
Don't show a pop up after the copy
Possibily only copy the files (pdf,jpeg,pptx) that are opened by the user
Here is what we've done so far:
' foreach.vbs
' Testing the for each function on files
'
' BEGIN
' Create a File System Object to handle files and folders
Set fso = CreateObject("Scripting.FileSystemObject")
' Some vars
src = "C:\" ' The source of search, should be changed before use
dest = "c:\temp\1\" ' destination where we will copy files to
' It would be a bright idead to force and/or create dest before
' starting copy
fso.CreateFolder(dest)
Set ofolder = fso.GetFolder(src) ' set as object
' get all files inside the specified folder
Set allfiles = ofolder.Files
' Enter a For Each Loop that will process each of the files
For Each sfile in allfiles
' Better get all extensions in lower case
If LCASE(fso.GetExtensionName(sfile.Name)) = "bat" then
' Print out what we find
wscript.echo sfile.Name
fso.CopyFile sfile, dest
End If
Next

If I get it right, your actual question is How to detect a USB drive has been plugged in?
You'll need some event driven language to do this, not VBScript unfortunately.
But if you don't want to go with programming, why not using Task Scheduler.
P.S. Actually, this topic (I not like the infinite cycle, but) is a possible answer.

Related

VBScript does not oFS.FileExists a file in oFS.CreateFolder

I'm having a strange problem with VBScript. I'd like to implement some other code with a following test:
If there is a file named like [that] in the [folder], do not copy it into the [folder].
Thing is, I found a strange relation in oFS.FileExists, I'm able to use it in a manually created folder, as long as I manually copy and paste a file into it. Then oFS.FileExists works like a charm.
Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")
filestr = "C:\where\file\is\file.file"
If (oFS.FileExists(filestr)) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
But it's not exactly my point. I'd like to test if a file is already in the desired folder, and such folder will be generated automatically with oFS.CreateFolder. But when it comes to testing an automatically generated folder, it's a different story.
Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")
oFS.CreateFolder(destination & objFoldername)
Initially I thought it might be something wrong with the file I'm looking for. I moved it to some other place and the oFS.FileExists found it. So I figured it might be the case of the folder itself. I can see the folder is a Read Only folder. I tested it in other manually created Read Only folder, also found it.
Finally I manually created the folder exactly like oFS.CreateFolder would do it, pasted manually a file into it and... it also found a file just fine.
As I witnessed, every test I conduct in a generated folder is failed, but done in a manually created one, pass.
Remarkable!
Had anyone such a case? Do you know why oFS.FileExists puts a blind eye on something created itself?
I'm using 64-bit Windows 10 Home, and I wrote both scrips in Visual Studio Code if that would be relevant.
Cheers guys, I can't be the first one.
EDIT for leeharvey1
Thank you leeharvey1 that you took a minute to have a look at this. This is the code that creates the directories:
Dim oFS, oFile, objShell, objFolder, sFolderPathspec, destination, file
Set oFS = CreateObject("Scripting.FileSystemObject")
sFolderPathspec = "C:\folder\where\files\are\"
Set objShell = CreateObject ("Shell.Application")
destination = "C:\folder\where\new\folders\with\files\are\intended\to\be\"
Set objFolder = objShell.Namespace(sFolderPathspec)
For Each file In objFolder.Items
name = file.Name
wykonano = objFolder.GetDetailsOf(file, 12)
If wykonano = "" Then
wykonano = objFolder.GetDetailsOf(file, 3)
End If
arr = Split(wykonano, " ")
brr = Split(arr(0), "-")
rok = brr(0)
miesiac = brr(1)
objFoldername = rok & "-" & miesiac
If CStr(oFS.FolderExists(destination & objFoldername)) >< "Prawda" Then
oFS.CreateFolder(destination & objFoldername)
End If
newdestination = destination & objFoldername & "\" & name
oFS.CopyFile sFolderPathspec & name, newdestination, False
Next
The whole testing for file existence started because I could not have the following to run:
oFS.CopyFile sFolderPathspec & name, newdestination, False
I would love it to copy but not overwrite. False, is however syntax correct, opposing to "Fałsz" (which would be correct in my Windows language). But the code crashes as soon as it hits the file that is already in the destination folder. Maybe should I have some kind of code which will let the sequence of code continue over the crashes caused by already existing files? (Like Python has)
So it took me to the following problem of testing for existence.
I figured I'll use the following method of the Files collection. As mentioned above, I get fails every time I conduct a test in generated folder, but done in a manually created one, pass.
That's the code (so far in a different VBScript file):
filestr = "C:\where\file\is\file.file"
Dim oFS
Set oFS = CreateObject("Scripting.FileSystemObject")
If oFS.FileExists(filestr) Then
MsgBox("Jest plik")
Else
MsgBox("Nie ma pliku")
End If
Function FileExists(FilePath)
Set oFS = CreateObject("Scripting.FileSystemObject")
If oFS.FileExists(FilePath) Then
FileExists=CBool(1)
Else
FileExists=CBool(0)
End If
End Function
If FileExists(filestr) Then
WScript.Echo "Does Exist"
Else
WScript.Echo "Does not exist"
End If
If (oFS.FileExists(filestr)) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
So, there are some details you wanted to know:
No, I am not working against a network shared file. It's all locally on my PC's ssd.
Have you tried disabling your anti-virus? No, if I'll need to do so in order to use it, I don't need the code.
I think I need to look for a file not for a folder, there is some kind of problem to locate the file. Do you think there could be also a problem to locate the folder itself?
Check folder Owner. Well, as far as I can see in Windows folder properties, it looks and have just the same settings as any other folder over there.
Thanks again leeharvey1 for your time!

Grab file name from file list, if file size greater than 1MB do copy

I have been set out by the following task by one of my managers at work:
We have a database of images for all our clothing styles and colours. For each type of clothing and for each colour we have 3 images. 2 of them are low resolution images and 1 of them is a high resolution image.
We need to copy the high res image for each style and colour from the old database which is made up of sub folders into one folder therefore ignoring the folder structure.
I have come across this Visual Basic script which is quite close to what I need but requires a few tweaks, as I am not really experienced with VB scripts I was hoping I could get some help here over at SO.
What I need to script to be tweaked to is:
-The script to read image names from a list (filelist.txt) (if possible without requiring to add the path for each image to the list, just the name and the extension which is .jpg)
-The script only needs to grab images if the size is greater than 1MB.
-The script to copy the images from sub-folders without keeping the folder structure.
Any and all help will be greatly appreciated, explanations behind the tweaks and any guidance will also be kind but not required.
Here is the script that I have so far. The paths are temporary as I was playing around with the script.
Option Explicit
' The source path for the copy operation.
Const strSourceFolder = "C:\Users\Cou Rou\Desktop\Old database"
' The target path for the copy operation.
Const strTargetFolder = "C:\Users\Cou Rou\Desktop\New database"
' The list of files to copy. Should be a text file with one file on each row. No paths - just file name.
Const strFileList = "C:\Users\Cou Rou\Desktop\Old database\filelist.txt"
' Should files be overwriten if they already exist? TRUE or FALSE.
Const blnOverwrite = FALSE
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1
Dim objFileList
Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False)
Dim strFileToCopy, strSourceFilePath, strTargetFilePath
On Error Resume Next
Do Until objFileList.AtEndOfStream
' Read next line from file list and build filepaths
strFileToCopy = objFileList.Readline
strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy)
strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
' Copy file to specified target folder.
Err.Clear
objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite
If Err.Number = 0 Then
' File copied successfully
Else
' Error copying file
Wscript.Echo "Error " & Err.Number & " (" & Err.Description & "). Copying " & strFileToCopy
End If
Loop

UFT File system test

Im a rookie on HP UFT testing and work on a data migration project I would like to automate.
Every day, we get a set of folder and files syncronize from a vendor with a following syncronization report(.csv file).
I would really like to test if the actual .csv file containing a list of files updated in the filesystem exists.
I get the .csv file on a network share, I open it and see a list of files with
data paths, which should be used to (loop)search though the filesystem and check if the files is actually on the location. How do I do that with UFT??
sample script to get all csv content and looping through content and verifying whether files exists or not.
filename = "C:\path\list.csv"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
filepath=f.ReadLine 'assuming every line as file full path
if FSO.fileexists(filepath) then
print filepath & " file is avaialble"
' do your checks here
else
print filepath & " file is not avaialble"
End if
Loop
f.Close

QTP: How to copy file from onle location and paste it into another and verify file count at the end

I need to write a vbscript for Copying files from local directory(Windows) to another(shared drive) and verify the counts at the end to make sure everything copied successfully. Any ideas on what the script will look like?
Here is what I recorded using GUI UFT:
SystemUtil.Run "C:\Users\Downloads"
Window("Documents").WinObject("Items View").WinList("Items View").Activate "Unified Functional Testing"
Window("Documents").WinObject("Items View").WinList("Items View").Select "APITest1"
Window("Documents").WinObject("ShellView").WinMenu("ContextMenu").Select "Copy"
Window("Documents").Restore Window("Documents").WinTreeView("WinTreeView").Select "Desktop;This PC;Downloads"
Window("Documents").WinObject("ShellView").WinMenu("ContextMenu").Select "Paste"
To copy files from one foler to another, Why do you record using QTP/UFT? The script recorded by QTP will not be reliable. (might not work everytime.) QTP supports VBScript. It is easy to copy files from one folder to another folder using VBScript.
To copy all files from temp1 to temp2 folder - just these 2 lines will do
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.CopyFile "C:\vIns\temp1\*.*" , "C:\vIns\temp2\" , TRUE
Once files are moved, You want to compare the files count. (I assume temp2 folder was empty before copying the files)
iTemp1Count = oFSO.getFolder("C:\vIns\temp1\").Files.Count
iTemp2Count = oFSO.getFolder("C:\vIns\temp2\").Files.Count
If iTemp1Count = iTemp2Count Then
Msgbox "all files are copied"
Else
Msgbox "Something is wrong!!!"
End If

Vbscripting to search for file via user input, calling functions to ask a series of questions to do tasks

First of all I'm really new into programming i have all these ideas on what i want to do but cannot seem to figure it out. Anyways i want a vbscript or batch file, anything at this point that when executed will ask for user input and say (Name of the file you want to search for). When i type in say hello.txt and hit enter it will then ask me another question saying where do you want me to look for these files. Then if i type in C:\ or any given drive letter it will search the entire drive letter directory including folders inside of folders if im not specific on actual path. Example c:\Program Files (x86)\ it will then search that directory and all of the folders in that directory and not the entire C:\ drive. I'm thinking to achieve this i need to call a function somehow that when i type something in a certain way it calls a function that runs a specific set of code. Example the second question asked file location so i type its location and it runs the code but replaces the location with the location i entered, this way its not only working for the location written into the code and can update and replace the line of code with user input of the location entered. Otherwise having it ask those questions were competently pointless if it doesn't have the ability to be able to replace parts of the code to adapt to user input and be more efficient, and not having to re write the script every single time you wanted to search for a new file.
Sorry lot of rambling on but i have looked everywhere found things like this but nothing close would be greatly appreciated if someone could help me out or point me in the rite direction.
This is what i have tryed for user input nothing close to what i want but here it is.
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)
It ask for your name and then says the name you entered i need this concept but when i type that in it calls a function and executes it. Hope someone knows what I'm talking about. Thanks
Here's a script to do that. I'll add comments to it later to explain what each part does. Right now it just outputs everything to a message box, but you can do what you want with it.
// Comments added
Dim fso, userfile, userdir, fileslist()
Set fso = CreateObject("Scripting.FileSystemObject")
ReDim fileslist(-1) ' Find results will be stored in this dynamic array
userfile = InputBox("Enter file to search for") ' Get file to search for
userdir = InputBox("Enter search directory") ' Get search directory
If Len(userfile) < 1 Then ' Check length of file name to ensure something was entered.
MsgBox "No file name entered", 4096 + 16 ' Message box. 4096 = "System modal", essentially always on top.
ElseIf Len(userdir) < 1 Then ' Check length of dir
MsgBox "No directory entered", 4096 + 16 ' 16 = exclamation/error
ElseIf Not fso.FolderExists(userdir) Then ' Make sure search directory actually exists
MsgBox "Folder " & userdir & " doesn't exist", 4096 + 16
Else
FindFile userfile, userdir ' Call FindFile sub, with the user's file and dir args passed to it
If UBound(fileslist) >= 0 Then ' After sub completes, check whether any results were found.
MsgBox Join(fileslist, vbCrLf), 4096, "Results" ' If so, output the whole array ("join"), one result per line (delimited with vbcrlf)
Else
MsgBox "File " & userfile & " not found", 4096 + 48 ' Otherwise file not found, message stating so
End If
End If
Sub FindFile(searchname, searchdir) ' Two parameters: file name, search directory
On Error Resume Next ' Enable error handling so we don't crash out on access denied errors
Dim file, folder, subfolder
For Each file In fso.GetFolder(searchdir).Files ' Process each file (as a file object) in the search directory
If LCase(searchname) = LCase(file.Name) Then ' See if file name matches. Using LCase to convert both to lowercase for case insensitivity.
ReDim Preserve fileslist(UBound(fileslist) + 1) ' If match found then increase array size by 1
fileslist(UBound(fileslist)) = file.Path ' Store the file path in newly added array entry
End If
Next
' Now the recursive bit. For any subfolders in current search directory, call FindFile again
' with (1) the same file name originally passed in as "searchname", and (2) a new search
' directory of the subfolder's name. FindFile then starts again on this new directory: finds files,
' adds matches to the fileslist array, then does the same on each subfolder found. This
' is how it searches each subfolder (and subfolders of subfolders... etc) in a directory
For Each subfolder In fso.GetFolder(searchdir).SubFolders
FindFile searchname, subfolder.Path
Next
On Error GoTo 0
End Sub

Resources