2012-09-20 62 views
0

我试图运行批处理脚本,该脚本将查找特定文件的最后修改日期。我使用类似于下面的脚本的内容:批处理脚本获取远程文件的最后修改日期

@echo off 

set mainDir=\\subdomain.myintranet.net\c$ 
set txtFile=%mainDir%\tmp.txt 
set txtFile2=%mainDir%\tmp2.txt 
set "bodyText=^<p^>Hello,^<br /^>^<br /^>" 

if exist %txtFile% (
    for %%X in (%txtFile%) do (set fileDate=%%~tX) 
    set "bodyText=%bodyText%tmp.txt file updated as of %fileDate%^<br /^>" 
) else (
    set "bodyText=%bodyText%Warning: Issues finding %txtFile%.^<br /^>" 
) 

if exist %txtFile2% (
    for %%X in (%txtFile2%) do (set fileDate2=%%~tX) 
    set "bodyText=%bodyText%tmp2.txt file updated as of %fileDate2%^<br /^>" 
) else (
    set "bodyText=%bodyText%Warning: Issues finding %txtFile2%.^<br /^>" 
) 

set "bodyText=%bodyText%^</p^>" 

echo %bodyText% > %mainDir%\mylog.txt 

测试此示例代码的时候,我发现它有时工作,有时没有。发生什么事是它找到了该文件,但fileDate变量回到空白。

我也尝试在脚本的开头放置一个空变量fileDate=,但那不起作用。

如果很重要:我已将批处理脚本连接到每日运行的SQL Server 2000作业。批处理文件和日志文件驻留在数据库所在的服务器上,但批处理脚本完全限定文件位置,如我在示例中所示(这是因为如果我想从我的桌面运行批处理文件,它将检查/更新正确的文件)。

由于提前, 约瑟夫

编辑:

输出应该是这样的:

Hello, 

tmp.txt file updated as of 9/19/2012 2:24 PM 
tmp2.txt file updated as of 9/19/2012 10:02 AM 

虽然我有时得到的是:

Hello, 

tmp.txt file updated as of 
tmp2.txt file updated as of 

而且其他时间我米ay得到:

Hello, 

tmp.txt file updated as of 9/19/2012 2:24 PM 
tmp2.txt file updated as of 

弄清楚发生了什么问题很混乱。

回答

3

呻吟......

这一定是与Windows批量开发中最常见的错误。您正试图扩展在同一代码块中设置的变量。但是,当整个代码块被解析时,变量会被扩展,所以您将获得在执行代码块之前存在的值。这显然不起作用。

从命令提示符下输入HELP SETSET /?并阅读有关延迟扩展的章节。这显示了你解决问题的一种方法。

但在你的情况下,你根本不需要变量,所以你不需要延迟扩展。

@echo off 

set mainDir=\\subdomain.myintranet.net\c$ 
set txtFile=%mainDir%\tmp.txt 
set txtFile2=%mainDir%\tmp2.txt 
set "bodyText=^<p^>Hello,^<br /^>^<br /^>" 

if exist %txtFile% (
    for %%X in (%txtFile%) do set "bodyText=%bodyText%tmp.txt file updated as of %%~tX^<br /^>" 
) else (
    set "bodyText=%bodyText%Warning: Issues finding %txtFile%.^<br /^>" 
) 

if exist %txtFile2% (
    for %%X in (%txtFile2%) do set "bodyText=%bodyText%tmp2.txt file updated as of %%~tX^<br /^>" 
) else (
    set "bodyText=%bodyText%Warning: Issues finding %txtFile2%.^<br /^>" 
) 

set "bodyText=%bodyText%^</p^>" 

echo %bodyText% > %mainDir%\mylog.txt 


编辑

有是为了简化,应该使代码更易于维护很多更多的空间:简单直接,当您添加到您的bodyText的使用FOR变量。由于您正在准备HTML文件,因此没有理由担心会出现额外的换行符,因此您不必将所有文本放入一个变量中。您可以使用多个ECHO语句。我会构建你的代码如下所示(未经测试,但概念是健全的):

@echo off 
setlocal 
set "mainDir=\\subdomain.myintranet.net\c$" 
set "br=^<br /^>" 
set "p=^<p^>" 
set "/p=^</p^>" 
>"%mainDir%\mylog.txt" (
    echo %p%Hello,%br%%br%" 
    for %%F in (
    "%mainDir%\tmp.txt" 
    "%mainDir%\tmp2.txt" 
) do (
    if exist %%F (
     echo %%~nxF file updated as of %%~tF%br%" 
    ) else (
     echo Warning: Issues finding %%~nxF.%br%" 
    ) 
    echo %/p% 
) 
+0

感谢您的解释!在阅读你的解释和变量的延迟扩展信息之后,这更有意义。并感谢关于简化代码的说明。我对我的制作脚本做了非常类似的更改,并且效果很好。再次感谢! –

相关问题