Vbs won't execute after function - vbscript

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

Related

list all files in a folder and sub folder without extention

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

Copying files from source folder to target folder

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.

The process cannot access the file because it is being used by another process. Code: 80070020, VBScript

When I run my vbscript, it says(In Windows Script Host):
C:\Users\admin\Desktop\Test.vbs
Line: 34
Char:1
Error: The process cannot access the file because it is being used by another process.
Code: 80070020
Source: (null)
How would I be able to fix this? Also here's the script...
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFSO, objFolder, objShell, objFile
Dim strDirectory, strFile
strDirectory = "c:\Folder"
strFile = "\Hidden.bat"
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
End If
set objFolder = nothing
set objFile = nothing
Const fsoForAppend = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTextStream
Set objTextStream = objFSO.OpenTextFile("C:\Folder\Hidden.bat", fsoForAppend)
objTextStream.WriteLine "attrib ""Folder"" +s +h"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run """C:\Folder\Hidden.bat"""
Set objShell = Nothing
Without creating any batch file to hide your folder :
Option Explicit
Dim objFSO,objFolder,strDirectory,Command,Result,objShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
strDirectory = "C:\Folder"
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End If
set objFolder = nothing
Command = "Cmd /c Attrib +s +h "& DblQuote(strDirectory) &""
Set objShell = CreateObject("WScript.Shell")
Result = objShell.Run(Command,0,True)
Set objShell = Nothing
'****************************************************************
Function DblQuote(str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************************
Closes an open TextStream file.
object.Close
From Help.
You need to close it after writing to it before using it.

Asking for a little assistance with cleanup and error

I have been given a task of creating a script that takes a log file (date is in the filename), pulls the data and posts it in event manager. I have a script that works as it should I know the script is ugly so please be gentle. I'm looking for 2 things.
some days nothing has happened and no log for the day was created. when this happens my script causes all kinds of slowness in the PC. I need help with a way for the script to not do its task if no new file has been added to the logs folder.
I would like a little help cleaning up the script.
Like i said i'm very new to this and i used scripts found on the web and fit them to do what i needed them to do.
any help would be greatly appricated.
Option Explicit
Const ForReading = 1
Dim strfolder
Dim FSO
Dim FLD
Dim fil
Dim strOldName
Dim strNewName
Dim strFileParts
Dim objShell
Dim objFSO
Dim objFolder
Dim strFileName
Dim objFile
Dim objTextFile
Dim strNextLine
Dim arrServiceList
Dim i
strFolder = "C:\Logs\"
Set objShell = CreateObject ("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(strFolder)
Set objShell = CreateObject ("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile ("C:\Logs\logCatchAll.log", ForReading)
For Each strFileName in objFolder.Items
If len(objFSO.GetExtensionName(strFileName)) > 0 Then
Set objFile = objFSO.GetFile(strFolder & strFileName.Name)
If DateDiff("H",objFile.DateLastModified,Now()) > 24 Then
objFSO.DeleteFile(strFolder & strFileName.Name),True
End If
End If
next
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FLD = FSO.GetFolder(strfolder)
For Each fil in FLD.Files
strOldName = fil.Path
If InStr(strOldName, "-") > 0 Then
strFileParts = Split(strOldName, "-")
strNewName = strFileParts(0) & ".log"
FSO.MoveFile strOldName, strNewName
End If
Next
Set FLD = Nothing
Set FSO = Nothing
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , ",")
For i = 3 to Ubound(arrServiceList)
objshell.LogEvent 4, arrServiceList(i)
Loop
You can block your Dim'd variables
You are reactivating the objShell to many times
You have a for loop at the bottom of your code without a Next statement.
You don't need to iterate through the log file until it reaches AtEndOfStream, just store it in a variable first.
You can use the same objFSO more than once if your not resetting the object.
You need to include error handling so you know where your code breaks.
Revised code.
Option Explicit
'Handle errors manually.
On Error Resume Next
'Set Constants
Const ForReading = 1
'Set Strings
Dim strFolder, strOldName, strNewName, strFileName, strFileParts, strNextLine, TFStrings
strFolder = "C:\Logs\"
'Set Objects
Dim objShell, objFSO, objFolder, objFile, objTextFile
Set objShell = CreateObject ("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objShell.Namespace(strFolder)
TFStrings = split(objFSO.OpenTextFile("C:\Logs\logCatchAll.log", ForReading).ReadAll, vbcrlf)
'Set Other Variables
Dim FLD, fil, arrServiceList, i, executed
executed = false
'Delete file procedure...
For Each strFileName in objFolder.Items
If len(objFSO.GetExtensionName(strFileName)) > 0 Then
Set objFile = objFSO.GetFile(strFolder & strFileName.Name)
If DateDiff("H",objFile.DateLastModified,Now()) > 24 Then
objFSO.DeleteFile(strFolder & strFileName.Name),True
executed = true
End If
End If
Next
If executed then
If err.number <> 0 then
'File was found, but delete was unsuccessful, log failure of delete.
executed = false
err.clear
Else
'Delete file procedure executed successfully. Lets move on.
executed = false
End If
Else
'No file was found within the conditions. log failure of search.
End if
'Move file and rename procedure...
Set FLD = objFSO.GetFolder(strfolder)
For Each fil in FLD.Files
strOldName = fil.Path
If InStr(strOldName, "-") > 0 Then
strFileParts = Split(strOldName, "-")
strNewName = strFileParts(0) & ".log"
objFSO.MoveFile strOldName, strNewName
executed = true
End If
Next
Set FLD = Nothing
Set FSO = Nothing
If executed then
If err.number <> 0 then
'File was found, but move was unsuccessful, log failure of move.
executed = false
err.clear
Else
'Move file procedure executed successfully. Lets move on.
executed = false
End If
Else
'No file was found within the conditions. log failure of search.
End if
For Each line in TFStrings
strNextLine = line
arrServiceList = Split(strNextLine , ",")
For i = 3 to Ubound(arrServiceList)
objshell.LogEvent 4, arrServiceList(i)
Next
Next

VBS script find and delete file

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.

Resources