这是我找到的符合我标准的代码。下面的代码用于将文件从源路径复制到目标路径。
隐含的条件: 仅当目标路径上不存在该文件或文件存在但文件较旧时才会覆盖源路径和目标文件。
如何在此代码中运行目标文件,以便目标文件仅在文件被覆盖或目标文件被新复制时运行?
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
答案 0 :(得分:0)
这是您脚本的重写和工作版本
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