在Windows批处理文件中,获取“文件名,目录名称或卷标语法不正确”。

时间:2013-12-16 18:01:09

标签: batch-file

我想将当前时间用作输出文件的标题,如下所示:

set NAME=%TIME%

然后我想写这个文件,如下:

echo words >> %NAME%

但是,当我尝试这样做时,会出现此错误:

  

文件名,目录名或卷标语法不正确。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

时间可能有冒号,例如10:58:31。冒号是Windows上文件名的无效字符。

编辑:

这是我之前用过时间戳的routine。只需将GET_TIMESTAMP逻辑复制到您的bat文件,然后使用您选择的格式(例如,MM-DD-YYYY)和输出变量(例如,TODAY)调用它。

@echo off
setlocal

call :GET_TIMESTAMP MM-DD-YYYY TODAY
echo %TODAY%
goto END

rem ========================================================
rem == http://kawishsiddiqui.wordpress.com/2013/01/10/batch-get_timestamp-function/
rem ========================================================
:GET_TIMESTAMP fmtString vResult
  set RepFormat=%1
  set MShortMap=01-Jan;02-Feb;03-Mar;04-Apr;05-May;06-Jun;07-Jul;08-Aug;09-Sep;10-Oct;11-Nov;12-Dec
  set MLongMap=01-January;02-February;03-March;04-April;05-May;06-June;07-July;08-August;09-September;10-October;11-November;12-December
  set DShortMap=01-Mon;02-Tue;03-Wed;04-Thu;05-Fri;06-Sat;07-Sun
  set DLongMap=01-Monday;02-Tuesday;03-Wednessday;04-Thursday;05-Friday;06-Saturday;07-Sunday
  set DShort2LongMap=Mon-Monday;Tue-Tuesday;Wed-Wednessday;Thu-Thursday;Fri-Friday;Sat-Saturday;Sun-Sunday
  :: a) Parse the date (e.g., Fri 02/08/2008)
        set cur_yyyy=%date:~10,4%
        set cur_yy=%date:~12,2%
        set cur_mm=%date:~4,2%
        set cur_dd=%date:~7,2%
        set cur_ddd=%date:~0,3%
  :: b) Parse the time (e.g., 11:17:13.49)
        set cur_hh=%time:~0,2%
        if %cur_hh% lss 10 (set cur_hh=0%time:~1,1%)
        set cur_nn=%time:~3,2%
        set cur_ss=%time:~6,2%
        set cur_ms=%time:~9,2%
  ::
  call set cur_mmm=%%MShortMap:*%cur_mm%-=%%
       set cur_mmm=%cur_mmm:;=&rem.%
  ::
  call set cur_mmmm=%%MLongMap:*%cur_mm%-=%%
       set cur_mmmm=%cur_mmmm:;=&rem.%
  ::
  call set cur_dddd=%%DShort2LongMap:*%cur_ddd%-=%%
       set cur_dddd=%cur_dddd:;=&rem.%
  ::
  call set RepFormat=%%RepFormat:B= %%
  call set RepFormat=%%RepFormat:C=,%%
  call set RepFormat=%%RepFormat:YYYY=%cur_yyyy%%%
  call set RepFormat=%%RepFormat:MMMM=%cur_mmmm%%%
  call set RepFormat=%%RepFormat:MMM=%cur_mmm%%%
  call set RepFormat=%%RepFormat:DDDD=%cur_dddd%%%
  call set RepFormat=%%RepFormat:DDD=%cur_ddd%%%
  call set RepFormat=%%RepFormat:YY=%cur_yy%%%
  call set RepFormat=%%RepFormat:MM=%cur_mm%%%
  call set RepFormat=%%RepFormat:DD=%cur_dd%%%
  call set RepFormat=%%RepFormat:HH=%cur_hh%%%
  call set RepFormat=%%RepFormat:MI=%cur_nn%%%
  call set RepFormat=%%RepFormat:SS=%cur_ss%%%
  call set RepFormat=%%RepFormat:MS=%cur_ms%%%
  set "%~2=%RepFormat%"
exit /b

:END
endlocal

答案 1 :(得分:2)

当前时间:导致问题。要从文件名中删除:,请将其替换为-或其他一些有效的文件名字符,如下所示。

set NAME = %TIME::=-%

当我在10:14 AM文件上运行时,会给出如下文件名(时间为test.bat

10-14-12.44