Hi I'm trying to copy a file from source to target folder. But I'm getting an error "Bad File name or number" when im running it.
Here is my code:
Option Explicit
Dim srcFolder, trgFolder
srcFolder = "\\sunpowercorp.com\spap\SPMM-QA\Public-Read_Write\SPMM QA Documents\Dominic Yumul\Toshiba Monthly Quality Report"
trgFolder = "http:\\dms\departments\QUALITY\Quality Ops in the Box\Quality Ops in the Box library\025 SPMM QA Staff Documents\Toshiba Monthly Quality Report"
CopyFilesAndFolders srcFolder, trgFolder
WScript.Quit
Sub CopyFilesAndFolders(ByVal strSource, ByVal strDestination)
Dim ObjFSO, ObjFolder, ObjSubFolder, ObjFile, files
Dim TargetPath
Set ObjFSO = CreateObject("scripting.filesystemobject")
'connecting to the folder where is going to be searched
Set ObjFolder = ObjFSO.GetFolder(strSource)
TargetPath = Replace (objFolder.path & "\", strSource, strDestination,1,-1,vbTextCompare)
If Not ObjFSO.FolderExists (TargetPath) Then ObjFSO.CreateFolder (TargetPath)
Err.clear
On Error Resume Next
'Check all files in a folder
For Each objFile In ObjFolder.files
If Err.Number <> 0 Then Exit For 'If no permission or no files in folder
On Error goto 0
If CheckToCopyFile (objFile.path, TargetPath & "\" & objFile.name) Then
objFSO.copyfile objFile.path, TargetPath & "\" & objFile.name, True
End If
Next
'Recurse through all of the subfolders
On Error Resume Next
Err.clear
For Each objSubFolder In ObjFolder.subFolders
If Err.Number <> 0 Then Exit For 'If no permission or no subfolder in folder
On Error goto 0
'For each found subfolder there will be searched for files
CopyFilesAndFolders ObjSubFolder.Path & "\", TargetPath & ObjSubFolder.name & "\"
Next
Set ObjFile = Nothing
Set ObjSubFolder = Nothing
Set ObjFolder = Nothing
Set ObjFSO = Nothing
End Sub
Function CheckToCopyFile(ByVal strSourceFilePath, ByVal strDestFilePath)
Dim oFSO, oFile, SourceFileModTime, DestFileModTime
CheckToCopyFile = True
Set oFSO = CreateObject("scripting.filesystemobject")
If Not oFSO.FileExists (strDestFilePath) Then Exit Function
Set oFile = oFSO.GetFile (strSourceFilePath)
SourceFileModTime = oFile.DateLastModified
Set oFile = Nothing
Set oFile = oFSO.GetFile (strDestFilePath)
DestFileModTime = oFile.DateLastModified
Set oFile = Nothing
If SourceFileModTime =< DestFileModTime Then CheckToCopyFile = False
Set oFSO = Nothing
End Function
I do not know what line I am getting the error.
On Windows Vista and newer you should be able to map SharePoint libraries to drive letters using WebDAV as described in this blog post:
Set net = CreateObject("WScript.Network")
net.MapNetworkDrive "X:", "\\sp.example.org#SSL\site\Shared Documents\"
Then copy your files to the mapped drive using FileSystemObject methods.
Related
This question already has answers here:
Copy a file from one folder to another using vbscripting
(5 answers)
Closed 2 years ago.
I want to make an automatic backup of my excel files using vbscript.
It works to copy the entire folder but I want to copy only the xlsx files.
Here is the code until now:
Dim objFSO, objFolder, evrFiles
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set evrFiles = objFolder.Files
For Each evrFile in evrFiles
If InStr(1, evrFile.Name, ".xlsx", vbBinaryCompare) > 0 Then
objFSO.CopyFile "C:\Users\Home\Desktop\vbs\" & evrFile.Name, "E:\test2"
End If
Next
WScript.Quit
It throws error on line 5 char 1 "Object required: " "
Any ideas?
LE: I have also tried:
Dim objFSO, objFolder
Set wshNetwork = CreateObject("WScript.Network")
strUser = wshNetwork.Username
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Users\" & strUser & "\Desktop\vbs")
Set evrFiles = objFolder.Files
For Each evrFile in evrFiles
If InStr(1, evrFile.Name, ".xlsx", vbBinaryCompare) > 0 Then
objFSO.CopyFile "C:\Users\" & strUser & "\Desktop\vbs\" & evrFile.Name, "E:\test2"
End If
Next
WScript.Quit
But this one gives me "Permission denied on line 9 char 3"
This one works(to copy the entire folder) but I want only the excel files.
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshNetwork = CreateObject("WScript.Network")
strUser = wshNetwork.Username
objFSO.CopyFolder"C:\Users\" & strUser & "\Desktop\vbs","E:\test2"
You dont need to iterrate each file, you could do something like:
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshNetwork = CreateObject("WScript.Network")
strUser = wshNetwork.Username
objFSO.CopyFile "C:\Users\" & strUser & "\Desktop\vbs\*.xlsx", "E:\test2\"
You may also want to set the overwrite flag when doing the copy, it there will be existing files already in the destination folder.
objFSO.CopyFile "C:\Users\" & strUser & "\Desktop\vbs\*.xlsx","E:\test2", True
Am setting up a vbs that I got from the web to copy some files from one folder to another.
Everything working fine in the code, except after the “end function”.
The script does not work anymore after Line 73.The sleep code as well as the wscript.shell does not execute after that.
Can someone please help.
Option Explicit
Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""C:\Program Files (x86)\VideoLAN\VLC\vlc.exe""")
WScript.sleep 5000
Dim ws
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM vlc.exe"
WScript.sleep 8500
Dim srcFolder, trgFolder,WshShell,UserProfilePath
Set WshShell = CreateObject("wscript.Shell")
UserProfilePath = WshShell.ExpandEnvironmentStrings("%UserProfile%")
srcFolder = "C:\Test\"
trgFolder = UserProfilePath & "\AppData\Roaming\"
CopyFilesAndFolders srcFolder, trgFolder
WScript.Quit
Sub CopyFilesAndFolders (ByVal strSource, ByVal strDestination)
Dim ObjFSO, ObjFolder, ObjSubFolder, ObjFile, files
Dim TargetPath
Set ObjFSO = CreateObject("scripting.filesystemobject")
'connecting to the folder where is going to be searched
Set ObjFolder = ObjFSO.GetFolder(strSource)
TargetPath = Replace (objFolder.path & "\", strSource, strDestination,1,-1,vbTextCompare)
If Not ObjFSO.FolderExists (TargetPath) Then ObjFSO.CreateFolder (TargetPath)
Err.clear
On Error Resume Next
'Check all files in a folder
For Each objFile In ObjFolder.files
If Err.Number <> 0 Then Exit For 'If no permission or no files in folder
On Error goto 0
If CheckToCopyFile (objFile.path, TargetPath & "\" & objFile.name) Then
objFSO.copyfile objFile.path, TargetPath & "\" & objFile.name, True
End If
Next
'Recurse through all of the subfolders
On Error Resume Next
Err.clear
For Each objSubFolder In ObjFolder.subFolders
If Err.Number <> 0 Then Exit For 'If no permission or no subfolder in folder
On Error goto 0
'For each found subfolder there will be searched for files
CopyFilesAndFolders ObjSubFolder.Path & "\", TargetPath & ObjSubFolder.name & "\"
Next
Set ObjFile = Nothing
Set ObjSubFolder = Nothing
Set ObjFolder = Nothing
Set ObjFSO = Nothing
End Sub
Sub CopyFilesAndFolders (ByVal strSource, ByVal strDestination)
Dim ObjFSO, ObjFolder, ObjSubFolder, ObjFile, files
Dim TargetPath
Set ObjFSO = CreateObject("scripting.filesystemobject")
'connecting to the folder where is going to be searched
Set ObjFolder = ObjFSO.GetFolder(strSource)
TargetPath = Replace (objFolder.path & "\", strSource, strDestination,1,-1,vbTextCompare)
If Not ObjFSO.FolderExists (TargetPath) Then ObjFSO.CreateFolder (TargetPath)
Err.clear
On Error Resume Next
'Check all files in a folder
For Each objFile In ObjFolder.files
If Err.Number <> 0 Then Exit For 'If no permission or no files in folder
On Error goto 0
If CheckToCopyFile (objFile.path, TargetPath & "\" & objFile.name) Then
objFSO.copyfile objFile.path, TargetPath & "\" & objFile.name, True
End If
Next
'Recurse through all of the subfolders
On Error Resume Next
Err.clear
For Each objSubFolder In ObjFolder.subFolders
If Err.Number <> 0 Then Exit For 'If no permission or no subfolder in folder
On Error goto 0
'For each found subfolder there will be searched for files
CopyFilesAndFolders ObjSubFolder.Path & "\", TargetPath & ObjSubFolder.name & "\"
Next
Set ObjFile = Nothing
Set ObjSubFolder = Nothing
Set ObjFolder = Nothing
Set ObjFSO = Nothing
End Sub
Function CheckToCopyFile (ByVal strSourceFilePath, ByVal strDestFilePath)
Dim oFSO, oFile, SourceFileModTime, DestFileModTime
CheckToCopyFile = True
Set oFSO = CreateObject("scripting.filesystemobject")
If Not oFSO.FileExists (strDestFilePath) Then Exit Function
Set oFile = oFSO.GetFile (strSourceFilePath)
SourceFileModTime = oFile.DateLastModified
Set oFile = Nothing
Set oFile = oFSO.GetFile (strDestFilePath)
DestFileModTime = oFile.DateLastModified
Set oFile = Nothing
If SourceFileModTime =< DestFileModTime Then CheckToCopyFile = False
Set oFSO = Nothing
End Function
WScript.sleep 8000
Dim objShell1
Set objShell1 = WScript.CreateObject( "WScript.Shell" )
objShell1.Run("""C:\Program Files (x86)\VideoLAN\VLC\vlc.exe""")
At line 23 you have WScript.Quit.
You do all the things at the beginning, taskkill, copy file and folders, and after that you close the script. If you want to run VLC, place the objShell1.Run("""C:\Program Files (x86)\VideoLAN\VLC\vlc.exe""") before line 23.
Something like:
Dim srcFolder, trgFolder,WshShell,UserProfilePath
Set WshShell = CreateObject("wscript.Shell")
UserProfilePath = WshShell.ExpandEnvironmentStrings("%UserProfile%")
srcFolder = "C:\Test\"
trgFolder = UserProfilePath & "\AppData\Roaming\"
CopyFilesAndFolders srcFolder, trgFolder
WScript.sleep 8000
Dim objShell1
Set objShell1 = WScript.CreateObject( "WScript.Shell" )
objShell1.Run("""C:\Program Files (x86)\VideoLAN\VLC\vlc.exe""")
WScript.Quit
I've come across the following script that I'd really like to use but I would like it not to have the .extention at the end
Dim fso
Dim ObjOutFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set ObjOutFile = fso.CreateTextFile("C:\Users\User\Movies.csv")
ObjOutFile.WriteLine("Type,File Name,Size")
GetFiles("E:\")
ObjOutFile.Close
Function GetFiles(FolderName)
On Error Resume Next
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = fso.GetFolder(FolderName)
Set ObjFiles = objfolder.Files
For Each ObjFile In ObjFiles
ObjOutFile.WriteLine("File," & ObjFile.Name & "," & objFile.Size & "," & objFile.Type)
Next
Set ObjSubFolders = ObjFolder.SubFolders
For Each ObjFolder In ObjSubFolders
ObjOutFile.WriteLine("Folder," & ObjFolder.Name)
GetFiles(ObjFolder.Path)
Next
End Function
I'm rubbish at this but I would really apperciate the help
Use the .GetBaseName() method of the FileSystemObject. As in:
>> WScript.Echo goFS.GetBaseName("c:\dir\name.ext")
>>
name
I have been working on the following VBS. This will search a parent folder and all child / subfolders and print any file with the provided extension (doc, docx, msg, ppt, txt) and came up with the following. I am new to VBS but I would like to define the file extensions to IGNORE, listing all others. I have the directory listing of each file type working but I don't want to have to set a NEXT for each file type. I was able to use the <> code in the top section to show all files that don't match an extension using:
If objFSO.GetExtensionName(strFileName) <> "jpg" then
But this doesn't work in the lower part:
if LCase(InStr(1,Files, "jpg")) > 1 then Wscript.Echo Files
I would also like to be able to define multiple file types; like
If objFSO.GetExtensionName(strFileName) <> "jpg" OR "jpeg" OR "tiff"
Lastly I need to output to a text file, not a windows script msg box.
Can anyone help? Sorry for typos or confusion, English is not my first language.
Dim fso
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set FSO = WScript.CreateObject("Scripting.Filesystemobject")
Set f = fso.CreateTextFile("C:\temp\output.txt", 2)
objStartFolder = "C:\Test"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "x937" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "docx" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "doc" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "txt" then
Wscript.Echo objFile.Name
End If
Next
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "msg" then
Wscript.Echo objFile.Name
End If
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "msg")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "txt")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "ppt")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "xls")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, "doc")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
End Sub
You can check all of the extensions in one loop:
For Each objFile in colFiles
Dim strFileName : strFileName = objFile.Name
Dim strExtension : strExtension = LCase(objFSO.GetExtensionName(strFileName))
If strExtension <> "txt" And _
strExtension <> "jpg" And _
strExtension <> "msg" And _
strExtension <> "docx" Then
Wscript.Echo objFile.Name
End If
Next
I just put a bunch of random extensions in because it wasn't clear which ones you want to ignore. Make sure you put them all in lowercase so the comparison works because the code converts the actual extension to lowercase.
For exporting the output to a txt file, the below code might work
Function TextFile_Generate()
strFile = "C:\...\ReportName.txt"
strValue = "output text..."
Set objFSO=CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strFile) Then
Set objFile = objFSO.OpenTextFile(strFile,8, True)
Else
Set objFile = objFSO.CreateTextFile(strFile,True)
End If
objFile.Write strValue & vbCrLf
objFile.Close
Set objFile = Nothing
Set objFSO =Nothing
End Function
I am trying to find a specific file on computer and delete it.
This is my code:
Const DeleteReadOnly = True
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oWshShell = CreateObject("WScript.Shell")
sDir = oWshShell.ExpandEnvironmentStrings("%temp%\dir.txt")
sFileName = "\date.vbs"
If oFSO.FileExists(sDir) Then oFSO.DeleteFile(sDir)
For Each oDrive In oFSO.Drives
if oDrive.DriveType = 2 Then Search oDrive.DriveLetter
Next
Set oFile = oFSO.OpenTextFile(sDir, 1)
aNames = Split(oFile.ReadAll, VbCrLf)
oFile.Close
For Each sName In aNames
If InStr(1, sName, sFileName, 1) > 0 Then WScript.Echo sName
Next
dim filesys
Set filesys = CreateObject("Scripting.FileSystemObject")
filesys.CreateTextFile "\date.vbs", True
If filesys.FileExists("\date.vbs") Then
filesys.DeleteFile "\date.vbs"
Wscript.Echo("File deleted")
End If
Sub Search(sDrive)
WScript.Echo "Scanning drive " & sDrive & ":"
oWshShell.Run "cmd /c dir /s /b " & sDrive & ":\" & sName & " >>" & sDir, 0, True
End Sub
The code is working only partially. When the file "date.vbs" is in root folder (C:\date.vbs) then it is deleted but when it is in folder (C:\backup\date.vbs) then it will not be deleted. Do you know which code changes I should make to be able to delete file even when it is not in root but anywhere in computer?
Thank you! V.
UPDATE:
The code is pretty much working right now. I just have a final problem of deleting the file. I am able to change the attributes from Read-only to normal but still i get the error of access denied.
This is my code:
Const DeleteReadOnly = True
Dim oFSO, oDrive, sFileName, ws, WshS, fso, usrProfile, oFolder, skypefolder
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFileName = "Skype.exe"
Set WshS = WScript.CreateObject("WScript.Shell")
usrProfile = WshS.ExpandEnvironmentStrings("%UserProfile%")
skypefolder = "C:\Program Files (x86)\Skype\"
For Each oDrive In oFSO.Drives
If oDrive.DriveType = 2 Then Recurse oFSO.GetFolder(skypefolder)
Next
Sub Recurse(oFolder)
Set oFile = CreateObject("Scripting.FileSystemObject")
Dim oSubFolder, oFile
If IsAccessible(oFolder) Then
For Each oSubFolder In oFolder.SubFolders
Recurse oSubFolder
Next
WScript.Echo oFolder.Path
For Each oFile In oFolder.Files
If oFile.Name = sFileName And oFile.Attributes And 1 Then
oFile.Attributes = 0
oFile.Delete True
End If
Next
End If
End Sub
Function IsAccessible(oFolder)
On Error Resume Next
IsAccessible = oFolder.SubFolders.Count >= 0
End Function
Thank you for help!
Code I use to run the script as ADMIN. After this it started to show the MessageBoxes. Before it was running in a console.
If WScript.Arguments.Named.Exists("elevated") = False Then
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ /elevated", "", "runas", 1
WScript.Quit
Else
Set oShell = CreateObject("WScript.Shell")
oShell.CurrentDirectory = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
'WScript.Echo("Now running with elevated permissions")
End If
So I believe there is something wrong in this code.
Your approach is much too complicated. Use a simple recursive function:
Option Explicit
Const DeleteReadOnly = True
Dim oFSO, oDrive, sFileName
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFileName = "date.vbs"
For Each oDrive In oFSO.Drives
If oDrive.DriveType = 2 Then Recurse oDrive.RootFolder
Next
Sub Recurse(oFolder)
Dim oSubFolder, oFile
If IsAccessible(oFolder) Then
For Each oSubFolder In oFolder.SubFolders
Recurse oSubFolder
Next
For Each oFile In oFolder.Files
If oFile.Name = sFileName Then
'oFile.Delete ' or whatever
End If
Next
End If
End Sub
Function IsAccessible(oFolder)
On Error Resume Next
IsAccessible = oFolder.SubFolders.Count >= 0
End Function
To achieve case-insensitive file name comparison, you could use
If StrComp(oFile.Name, sFileName, vbTextCompare) = 0 Then
As an exercise: You can also use the WMI Service to find certain files. You don't have to go through all folders, you just query the file on any drive, on any folder:
Function find_file(filename)
Dim objWMIService, colItems, objItem, strComputer
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM CIM_DataFile WHERE FileName='" & filename & "'",,48)
For Each objItem in colItems
msgbox "Found " & objItem.Name & " in " objItem.Path
Next
End Function
Note: It can take long before the function has returned its results.