Here's the code that I found which matches my criteria. The code below is used to copy file from source path to target path.
Conditions implied:
Only if the file doesn't exist on the target path or if the file exists but its older then the source path and the target file is overwritten.
How do I run a target file within this code so that the target file runs only when the file is being overwritten or the target file is freshly copied?
Option Explicit
Dim WshShell
Dim fso
Dim USERPROFILE
Dim srcPath
Dim tgtPath
On Error Resume Next
Set WshShell = WScript.CreateObject("Wscript.Shell")
Set fso = WScript.CreateObject("Scripting.FilesystemObject")
'USERPROFILE = WshShell.ExpandEnvironmentStrings("%USERPROFILE%")
srcPath = "C:\test.exe"
tgtPath = "D:\"
If Not fso.FileExists(tgtPath) Then
fso.CopyFile srcPath, tgtPath, True
ElseIf fso.FileExists(srcPath) Then
ReplaceIfNewer srcPath, tgtPath
End If
Sub ReplaceIfNewer(strSourceFile, strTargetFile)
Const OVERWRITE_EXISTING = True
Dim objFso
Dim objTargetFile
Dim dtmTargetDate
Dim objSourceFile
Dim dtmSourceDate
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objTargetFile = objFso.GetFile(strTargetFile)
dtmTargetDate = objTargetFile.DateLastModified
Set objSourceFile = objFso.GetFile(strSourceFile)
dtmSourceDate = objSourceFile.DateLastModified
If (dtmTargetDate < dtmSourceDate) Then
objFso.CopyFile objSourceFile.Path, objTargetFile.Path,OVERWRITE_EXISTING
End If
Set objFso = Nothing
End Sub
Here a reworded and working vesion of your script
option explicit
dim WshShell, fso, srcPath, tgtPath , file, objFileSrc, objFileTgt
const OVERWRITE = true
set WshShell = WScript.CreateObject("Wscript.Shell")
set fso = WScript.CreateObject("Scripting.FilesystemObject")
file = "test.exe"
srcPath = "c:\"
tgtPath = "e:\"
if fso.FileExists(srcPath & file) then
if not fso.FileExists(tgtPath & file) then
'target doesn't exist, just copy
fso.CopyFile srcPath & file, tgtPath
wscript.echo srcPath & file & " copied to " & tgtPath & file
else
Set objFileSrc = fso.getFile(srcPath & file)
Set objFileTgt = fso.getFile(tgtPath & file)
'target exists, compare dates
if objFileSrc.DateLastModified > objFileTgt.DateLastModified then
fso.CopyFile srcPath & file, tgtPath, OVERWRITE
wscript.echo srcPath & file & " copied over " & tgtPath & file
else
wscript.echo srcPath & file & " not newer then " & tgtPath & file
end if
end if
else
wscript.echo srcPath & file & " does not exist"
end if
set fso = Nothing
Related
I am looking to create a script that will compare the last modified date of up to 4 files then capture the one most recently modified. My current road block is that some files might not exist.
The set will fail if the file does not exist but I can easily overcome that by looking for the file and if it does not exist simply skip the set command. This would cause the creation of the array to fail because my variable is now blank.
Any suggestions how to resolve this?
Here is what I have so far:
Option Explicit
Dim objFSO, path, file, recentDate, recentFile, File1, File2, File3, File4, afiles, File1date, date1
Set objFSO = CreateObject("Scripting.FileSystemObject")
set File1=objFSO.getfile("c:\temp\file.txt")
set File2=objFSO.getfile("c:\test\File.txt")
set File3=objFSO.getfile("c:\users\%profile%\documents\File.txt")
set File4=objFSO.getfile("c:\users\public\documents\File.txt")
'Prepare variables to store the required information
Dim dateMin, dateMax
date1 = File1.datelastmodified
wscript.echo date1
wscript.echo now
dateMin = date1
dateMax = date1
afiles = Array( File1.datelastmodified, File2.datelastmodified, File3.datelastmodified, File4.datelastmodified )
Dim i
For i=1 to UBound(aFiles)
If aFiles(i) < dateMin Then dateMin = aFiles(i)
if aFiles(i) > dateMax Then dateMax = aFiles(i)
Next
'
' Output Information
WScript.Echo "Highest: " & CStr( dateMax )
WScript.Echo " Lowest: " & CStr( dateMin )
I think this would be much easier if you use an ArrayList to capture the DateLastModified for each file.
An ArrayList lets you dynamically add values unlike a VBScript Array.
Furthermore, the ArrayList has a very useful method called Sort() we can use here to determine the dateMin and dateMax values.
Try:
Option Explicit
Dim objFSO, objList, objFile, arrFiles, fileName
arrFiles = Array("c:\temp\file.txt","c:\test\File.txt","c:\users\%profile%\documents\File.txt","c:\users\public\documents\File.txt")
Set objList = CreateObject("System.Collections.ArrayList")
Set objFSO = CreateObject("Scripting.FilesystemObject")
For Each fileName In arrFiles
If objFSO.FileExists(fileName) Then
Set objFile = objFSO.GetFile(fileName)
objList.Add objFile.DateLastModified
End If
Next
objList.Sort()
' Prepare variables to store the required information
Dim dateMin, dateMax
dateMin = objList.item(0)
dateMax = objList.item(objList.Count - 1)
' Output Information
WScript.Echo "Highest: " & CStr( dateMax )
WScript.Echo "Lowest: " & CStr( dateMin )
' Clean up
Set objFSO = Nothing
Set objFile = Nothing
Set objList = Nothing
Edit
The above code was a remake of your original code. I may have misunderstood then that your goal is to find the file most recently modified.
This should do what you have in mind:
Option Explicit
Dim objFSO, objFile, objLatest, fileName, arrFiles
arrFiles = Array("c:\temp\file.txt","c:\test\File.txt","c:\users\%profile%\documents\File.txt","c:\users\public\documents\File.txt")
Set objFSO = CreateObject("Scripting.FilesystemObject")
Set objLatest = Nothing
For Each fileName In arrFiles
If objFSO.FileExists(fileName) Then
Set objFile = objFSO.GetFile(fileName)
If (objLatest Is Nothing) Then
Set objLatest = objFile
ElseIf (objFile.DateLastModified > objLatest.DateLastModified) Then
Set objLatest = objFile
End If
End If
Next
If objLatest Is Nothing Then
WScript.Echo "None of the files in 'arrFiles' exist.."
Else
' Here you decide if you want to keep the latest file as Object (-> objLatest) or just as a string to the full pathname of that file
Dim latestFile
latestFile = objFSO.GetAbsolutePathName(objLatest) ' store the full path and filename
' Info on FormatDateTime() at https://www.w3schools.com/asp/func_formatdatetime.asp
WScript.Echo "Most recently modified file is '" & latestFile & "' at " & FormatDateTime(objLatest.DateLastModified, 0)
End If
' Clean up
Set objFSO = Nothing
Set objFile = Nothing
Set objLatest = Nothing
I needed to copy all of my photos from my old laptop to my new laptop. This is a quick and dirty script that I put together (based on other scripts on this site) to copy files from one network location to another. I wanted the process to be able to recover in case of a network copy error because the total time to copy all of my photos was 40 hours.
sourceRoot and targetRoot is the beginning part of the file path to replace between locations. lastFileLog is a file used to keep track of the last file that was copied. This is needed to recover from a partial copy. Windows seems to allocate the full file size even when the file fails to copy. So I just keep track of the last file to copy it again on failure. objStartFolder is the starting path on the source network location.
'initialize paths
objStartFolder = "\\owner-pc\d\pics"
lastFileLog = "c:\Files\misc\archive.log"
sourceRoot = "\\owner-pc\d"
targetRoot = "c:\Files"
Set objFSO = CreateObject("Scripting.FileSystemObject")
'read log
Set objFile = objFSO.OpenTextFile(lastFileLog)
Do Until objFile.AtEndOfStream
replacefile= objFile.ReadLine
Wscript.Echo "This file will be replaced: " & replacefile
Loop
objFile.Close
'copy files
Set objFolder = objFSO.GetFolder(objStartFolder)
ShowSubfolders objFSO.GetFolder(objStartFolder)
'clear log
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write ""
objFileLog.Close
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
if not(objFSO.FolderExists(replace(Subfolder.Path,sourceRoot,targetRoot))) then
objFSO.CreateFolder(replace(Subfolder.Path,sourceRoot,targetRoot))
end if
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
if not(objFSO.FileExists(replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot))) then
Wscript.Echo Subfolder.Path & "\" & objFile.Name
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write Subfolder.Path & "\" & objFile.Name
objFileLog.Close
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot)
elseif replacefile = Subfolder.Path & "\" & objFile.Name then
Wscript.Echo "Replacing ... " & Subfolder.Path & "\" & objFile.Name
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot),true
else
Wscript.Echo "Skip ... " & Subfolder.Path & "\" & objFile.Name
end if
Next
ShowSubFolders Subfolder
Next
end sub
For Folder: Try This.
Option Explicit
Dim obj,Itemcoll1,a,b
Set obj=CreateObject("Shell.Application")
Function SelectFold1(Desc)
Set SelectFold1=obj.BrowseForFolder(0,Desc,0,"C:\Users\Mohammed Sajjad\Desktop\")
End Function
Set Itemcoll1=SelectFold1("Copy: ").Items
SelectFold1("Paste: ").CopyHere Itemcoll1 'Use MoveHere if you want to move
MsgBox "Completed"
For File:
Option Explicit
Dim objApp : Set objApp = CreateObject("Shell.Application")
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objSHL : Set objSHL = CreateObject("WScript.Shell")
'Browse for Folder
'----------------------------------------------------------
Function SelectFold()
Dim objFolder
Set objFolder = objApp.BrowseForFolder(0,"Select a Folder",0,0)
If objFolder Is Nothing Then
MsgBox "Canceled"
WScript.Quit
Else
SelectFold = objFolder.Self.Path & "\"
End If
End Function
'----------------------------------------------------------
'Browse for file
'----------------------------------------------------------
Function SelectFile()
Dim tempFolder : Set tempFolder = objFSO.GetSpecialFolder(2)
Dim tempFile : tempFile = objFSO.GetTempName() & ".hta"
Dim path : path = "HKCU\Volatile Environment\MsgResp"
With tempFolder.CreateTextFile(tempFile)
.Write "<input type=file name=f>" & _
"<script>f.click();(new ActiveXObject('WScript.Shell'))" & _
".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value);" & _
"close();</script>"
.Close
End With
objSHL.Run tempFolder & "\" & tempFile, 0, True
If objSHL.RegRead(path) = "" Then
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
WScript.Quit
End If
SelectFile = objSHL.RegRead(path)
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
End Function
'----------------------------------------------------------
objFSO.CopyFile SelectFile, SelectFold
I had a script which worked on win xp but beacuse some of the methods are not available anymore I had to rewrite the script and use mshta.exe.
VBS script should do two things:
Read from file
Parse the info to the batch file
I have done the 1st bit but in the 2nd part I am getting an error. Could you please point me to the right direction?
Option Explicit
Dim objFso
Dim strFileName
Dim strFile
Dim objShell
Dim cimv2
Dim RemoteMachine
Dim YesNo
Dim out
Dim crt
Dim objDialog, intResult
Dim objTextFile, strText, iintresult
Dim objExec, strMSHTA, wshShell
mainMenu
Sub mainMenu()
do
out = inputbox("Choose option:" & vbcr & "1 - Deployment" & vbcr & "0 - Exit", "Menu", "0")
If out="1" then
call SelectFile
End If
If out="0"
then WScript.Quit
End if
loop
End Sub
Sub bgInfo(param)
YesNo = Msgbox("deployment? " & param, 4)
if YesNo = vbYes Then
do while not strMSHTA.AtEndOfStream
RemoteMachine = strMSHTA.ReadLine()
On Error Resume Next
objShell.Run "bginfo.bat " & RemoteMachine, 1, true
On Error Goto 0
loop
end if
End Sub
Sub SelectFile( )
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
intResult = objExec.StdOut.ReadLine( )
msgbox iintresult
If intResult <> "" Then
call bgInfo(intResult)
End If
Set objExec = Nothing
Set wshShell = Nothing
End Sub
Set objFso = Nothing
Set strFileName = Nothing
Set strFile = Nothing
Set objShell = Nothing
Set cimv2 = Nothing
Set RemoteMachine = Nothing
Set fso = Nothing
I am getting an error in line 33 char 5
Error: Object required: strMSHTA
thank you! :)
I had to add this code:
Set objFso = CreateObject("Scripting.FileSystemObject")
set strFile = objFso.OpenTextFile(param2, 1, True)
Set objShell = WScript.CreateObject("Wscript.Shell")`
I have a VBS file that I am trying to use to determine what folders and files are in a certain directory. I believe I have the code written correctly, but whenever I try to write out the file or current directory I get a blank text document with nothing but the root directory written out. Any advice would be greatly appreciated.
Dim NewFile
Function GetFolders (strFolderPath)
Dim objCurrentFolder, colSubfolders, objFolder, files
Set objCurrentFolder = objFSO.GetFolder(strFolderPath)
Set colSubfolders = objCurrentFolder.SubFolders
For Each objFolder In colSubfolders
NewFile.WriteLine(" - " & objFolder.Path)
Set files = folder.Files
For each folderIdx In files
NewFile.WriteLine(" - "& folderIdx.Name)
Next
Call GetFolders (objFolder.Path)
Next
End Function
Dim fso, sFolder
Set fso = CreateObject("Scripting.FileSystemObject")
sFolder = Wscript.Arguments.Item(0)
If sFolder = "" Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If
Set NewFile = fso.CreateTextFile(sFolder&"\FileList.txt", True)
NewFile.WriteLine(sFolder)
Call GetFolders(sFolder)
NewFile.Close
You haven't payed sufficient attention to your variable naming. Your script is a good example of the reason why all VBScripts should start with the line:-
Option Explicit
This would highlight all the variables that haven't been declared which in turn will point out typos and inconsistencies in variable naming. Here is how I would write it:-
Option Explicit
Dim msFolder : msFolder = Wscript.Arguments.Item(0)
If msFolder = "" Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If
Dim mfso : Set mfso = CreateObject("Scripting.FileSystemObject")
Dim moTextStream : Set moTextStream = mfso.CreateTextFile(msFolder & "\FileList.txt", True)
moTextStream.WriteLine(msFolder)
WriteFolders mfso.GetFolder(msFolder)
moTextStream.Close
Sub WriteFolders(oParentFolder)
Dim oFolder
For Each oFolder In oParentFolder.SubFolders
moTextStream.WriteLine(" - " & oFolder.Path)
Dim oFile
For Each oFile In oFolder.Files
moTextStream.WriteLine(" - " & oFile.Name)
Next
WriteFolders oFolder
Next
End Sub
I got the code
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"ex3")> 0 Then
strLine = Replace(strLine,"ex3","ex5")
End If
WScript.Echo strLine
Loop
The strLine replacing part i can fix myself to use with my own purposes, but how do i do something like this so that it doesn't require the file's name, it just edits all text files within the document?
you can do it like this,
strFolder = "c:\myfolder"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName =strFile.Name
strFilePath = strFile.Path
strFileExt = objFS.GetExtensionName(strFile)
If strFileExt = "txt" Then
Set objFile = objFS.OpenTextFile(strFile)
' your current code here..
objFile.Close()
End If
Next