如何获取未命名文件的名称



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

假设文件没有被复制或重命名。我想在我的脚本中包含一个命令,显示"data.csv"由于zyx原因而不复制或重命名。

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

我的编码:

@echo off
setlocal
set DateFolder=04.2013
set TargetFolder=F:FinancialData%DateFolder%Final Reports
:: copy the newest file from AccruntPnLMTD and rename it to PNL.csv
call :copyAndRename "F:FinancialDataReportsAccruntPnLMTD" "%TargetFolder%PNL.csv"
:: copy the newest file from AccountPnlMTD and rename it to AC.csv
call :copyAndRename "F:FinancialDataReportsAccountPnlMTD" "%TargetFolder%AC.csv"
:: copy the newest file from ExpensesMTD and rename it to EXPMTD.csv
call :copyAndRename "F:FinancialDataReportsExpensesMTD" "%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

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失败时,它将错误级别设置为1。通过测试错误级别,可以在发生错误时打印源文件的名称。错误消息由copy在前一行中提供。

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

正如本文所解释的,脚本的输出可以重定向到一个文件,用于使用语法> logfile 2>&1进行日志记录。假设根据注释,日志文件为F:FinancialData,则命令行将变为

myscript.bat > F:FinancialData 2>&1
@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

最新更新