如何获取未透明文件的名称

时间:2013-12-06 09:36:05

标签: batch-file file-io

我有源和目标路径。 从源路径,任何.xls文件都将复制到目标路径,并将重命名为“data.csv”

假设文件未被复制或重命名。 我想在我的脚本中包含一个命令,该命令显示“data.csv”因zyx原因而无法复制或重命名。

所以我可以跟踪&解决问题。

我的编码:

@echo off
setlocal
set DateFolder=04.2013
set TargetFolder=F:\Financial\Data\%DateFolder%\Final Reports

:: copy the newest file from AccruntPnLMTD and rename it to PNL.csv
call :copyAndRename "F:\Financial\Data\Reports\AccruntPnLMTD" "%TargetFolder%\PNL.csv"

:: copy the newest file from AccountPnlMTD and rename it to AC.csv
call :copyAndRename "F:\Financial\Data\Reports\AccountPnlMTD" "%TargetFolder%\AC.csv"

:: copy the newest file from ExpensesMTD and rename it to EXPMTD.csv
call :copyAndRename "F:\Financial\Data\Reports\ExpensesMTD" "%TargetFolder%\EXPMTD.csv"


:: Done
goto :eof

:copyAndRename
set SourceFolder=%~1
set TargetFile=%~2

:: Find the newest file in the source folder
for /f "tokens=*" %%F in ('dir /b /od /a-d "%SourceFolder%"') do set "NewestFile=%%F"

:: copy and rename it to the target
copy "%SourceFolder%\%NewestFile%" "%TargetFile%"


:: Done with this subroutine
goto :eof

2 个答案:

答案 0 :(得分:1)

forcopy命令在遇到错误时始终会打印一条消息,因此无需关心它们。如果要为源文件夹中未复制的每个文件打印一个警告,因为它比最新文件旧,可以通过第二次迭代显式执行。

:copyAndRename
set SourceFolder=%~1
set TargetFile=%~2

:: Find the newest file in the source folder
for /f "tokens=*" %%F in ('dir /b /od /a-d "%SourceFolder%"') do set "NewestFile=%%F"

for /f "tokens=*" %%F in ('dir /b /od /a-d "%SourceFolder%"') do (
    if NOT "%%F" == "%SourceFolder%\%NewestFile%" echo "%%F" not copied because it is an older file.
)

:: copy and rename it to the target
copy "%SourceFolder%\%NewestFile%" "%TargetFile%"

:: Done with this subroutine
goto :eof

您的copyAndRename函数假定每个源文件夹中至少有一个文件且没有子目录。如果不是这种情况,您应该为代码添加额外的逻辑,否则,%NewestFile%将不会被设置,或者它将保留上一次调用copyAndRename的值,或者它将命名为copy不复制的目录。

<强>更新

copy失败时,它将errorlevel设置为1.通过测试errorlevel,可以在发生错误时打印源文件的名称。错误消息由前一行中的copy提供。

:: copy and rename it to the target
copy "%SourceFolder%\%NewestFile%" "%TargetFile%"
if errorlevel 1 echo File "%SourceFolder%\%NewestFile%" not copied.

this post中所述,脚本的输出可以重定向到文件,以使用语法> logfile 2>&1进行记录。根据注释假设日志文件为F:\Financial\Data,命令行将变为

myscript.bat > F:\Financial\Data 2>&1

答案 1 :(得分:0)

@ECHO OFF &SETLOCAL
set flag=%random%
(for /f "delims=" %%a in ('dir /b /a-d /o-d') do (
    if not defined %flag% (
        echo copy "sourcefolder\%%~a" "targetfolder">con
        set %flag%=%random%
    ) else (
        echo Not copied: %%~a
    )
))>nocopy.log
type nocopy.log