复制并重命名最新文件

时间:2013-07-16 12:34:07

标签: windows batch-file vbscript cmd directory

我想将源路径中的最新文件复制到目标路径,然后重命名如下:

目标路径:C; \ User \ Client1 \ FinalReports

源路径:C:\ User \ Client1 \ Reports \ ReportFolderA(来自Report FolderA的文件应重命名为File1.csv作为目标文件夹)         C:\ User \ Client1 \ Reports \ ReportFolderB(报告FolderB中的文件应重命名为目标文件夹为File2.csv)         C:\ User \ Client1 \ Reports \ ReportFolderD(报告FolderD中的文件应重命名为目标文件夹为File4.csv)         C:\ User \ Client1 \ Reports \ ReportFolderF(报告文件夹中的文件应重命名为目标文件夹为File5.csv)

“C:\ User \ Client1 \ Reports”源路径已修复,后跟变量ReportFolderA,ReportFolderB.etc..so我们只能在脚本中设置一个源路径。

我需要一个脚本来通过浏览弹出方法来选择路径。在哪里我只选择两个路径“source& target”

通过浏览弹出窗口,因为下次我会有不同的位置,我们无法在一次脚本中修复它们。我想根据需要运行脚本。

2 个答案:

答案 0 :(得分:3)

尝试这样的方法来复制文件夹中的最新文件:

@echo off

setlocal

set "src=C:\User\Client1\Reports\ReportFolderA"
set "dst=C:\User\Client1\FinalReports"

pushd "%src%"
for /f "delims=" %%f in ('dir /b /a:-d /o:-d') do (
  copy "%%~f" "%dst%\File1.csv"
  goto next
)

:next
popd

在VBScript中,您可以使用Shell.BrowseForFolder方法选择文件夹。选择源文件夹的示例:

Set os = CreateObject("Shell.Application")
basedir = os.Namespace("C:\").Self.Path
Set fldr = os.BrowseForFolder(0, "Select source folder:", &h10&, basedir)

If fldr Is Nothing Then
  WScript.Echo "User pressed [Cancel]."
  WScript.Quit 1
End If

src = fldr.Self.Path

查找和复制文件夹中的最新文件可以这样实现:

Set fso = CreateObject("Scripting.FileSystemObject")
Set mostRecent = Nothing
For Each f In fso.GetFolder(src).Files
  If mostRecent Is Nothing Then
    Set mostRecent = f
  ElseIf f.DateLastModified > mostRecent.DateLastModified Then
    Set mostRecent = f
  End If
Next

If Not mostRecent Is Nothing Then
  mostRecent.Copy fso.BuildPath(dst, "File1.csv")
End If

答案 1 :(得分:1)

试试这个:

@echo off &setlocal
set "src=C:\User\Client1\Reports\ReportFolderA"
set "dst=C:\User\Client1\FinalReports"

cd /d "%src%"
for /f "delims=" %%a in ('dir /b /a-d /od') do set "file=%%~a"
copy "%file%" "%dst%\File1.csv"
相关问题