这是我找到的符合我的条件的代码。下面的代码用于将文件从源路径复制到目标路径。
隐含条件:仅当文件在目标路径上不存在或文件存在但较旧时,才会覆盖源路径和目标文件。
如何在此代码中运行目标文件,以便目标文件仅在文件被覆盖或目标文件被新复制时运行?
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