【问题标题】:Copy and Rename newest file复制并重命名最新文件
【发布时间】:2013-07-14 15:22:18
【问题描述】:

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

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

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

“C:\User\Client1\Reports”源路径是固定的,后面跟着变量ReportFolderA,ReportFolderB.etc..所以我们可以在脚本中只设置一个源路径。

我需要一个脚本来通过浏览弹出方法选择路径。我只会选择两个路径“源和目标”

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

【问题讨论】:

  • 我认为“我想制作一个脚本”实际上是指“我希望其他人为我制作一个脚本”?

标签: windows batch-file vbscript cmd directory


【解决方案1】:

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

@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

【讨论】:

  • thx Ansgar ...但我想在弹出窗口中提供路径,询问源路径和目标路径。
  • Batch 不是解决此问题的正确工具。您可能需要考虑切换到 VBScript。
  • 哦,太好了...你能帮我做吗?
  • 我试了一下,它只询问源路径
  • @AnsgarWiechers +1 写了这么好的代码(获取源路径),以至于 niki niki 期望它也能获取目标路径(和世界统治?)。
【解决方案2】:

试试这个:

@echo off &setlocal 设置“src=C:\User\Client1\Reports\ReportFolderA” 设置“dst=C:\User\Client1\FinalReports” cd /d "%src%" for /f "delims=" %%a in ('dir /b /a-d /od') 设置 "file=%%~a" 复制 "%file%" "%dst%\File1.csv"

【讨论】:

  • 我想在浏览弹出窗口中给出路径。这也不是唯一的一个来源,有 4-5 个源路径,文件需要修改和重命名。
猜你喜欢
  • 1970-01-01
  • 2018-11-29
  • 2013-06-13
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2011-03-18
  • 2020-05-16
  • 2016-08-04
相关资源
最近更新 更多