我正在尝试在我的本地机器上运行一个批处理脚本,它将处理某些服务器上的一些日志归档。我可以通过文件资源管理器“\SERVERNAME\C$\SOME FOLDER”访问服务器。当我尝试从本地 xcopy 从源到目标并附加时间戳时,它就像 TIMESTAMP 变量不存储我的日期/时间串联。
这是针对 Windows 2012r2 服务器,我尝试只将日期\时间附加到最后,效果很好,但是,它不是我正在寻找的所需格式,它开始将目录与日期嵌套但没有时间和它看起来一团糟。:(
我也尝试过使用 wmic,但是这是我第一次编写批处理文件来自动执行某些任务,因此所有这些都是一次很棒的学习体验。
我试过了echo %TIMESTAMP%
,没有任何回报?我什至尝试将串联(%CUR_YYYY%%CUR_MM%%CUR_DD%-%CUR_HH%%CUR_NN%%CUR_SS%)
直接添加到文件目录中,但它不起作用:(
REM Check to see if a service on the machine is stopped (it is always stopped by the time it gets here) before we move the files from the logging directory to a new one.
for /F "tokens=3 delims=: " %%H in ('sc \\REMOTESERVER query "SOME SERVICE NAME" ^| findstr " STATE"') do (
if /I "%%H" == "STOPPED" (
REM substring the date and time and then concat it together at the end to make the desired timestamp variable
set CUR_YYYY = %date:~10,4%
set CUR_MM = %date:~4,2%
set CUR_DD = %date:~7,2%
set CUR_HH = %time:~0,2%
set CUR_NN = %time:~3,2%
set CUR_SS = %time:~6,2%
set CUR_MS = %time:~9,2%
set TIMESTAMP = %CUR_YYYY%%CUR_MM%%CUR_DD%-%CUR_HH%%CUR_NN%%CUR_SS%
REM copy files from the servers source directory and then move the files to a newly created logging folder with a timestamp appened at the end
echo d | xcopy /f /y "\\REMOTE SERVER\src" "\\REMOTE SERVER\dest\Logging_%TIMESTAMP%" /E /I
REM delete the contents of the servers source directory to keep things nice and clean
pushd \\REMOTE SERVER\src && del . /F /Q popd
)
)
预期结果如下: 服务器上的 SourceFolder 将在那里,但空的 DestinationFolder 将创建一个新的 Logging 文件夹 Logging_20190325010101 并且在新创建的日志文件夹中,SourceFolder 中的所有内容都应该在那里。
您需要=
在 set 命令之前和之后去除空格,此外,您需要delayedexpansion
在代码块中更改变量,并且有更好的方法来去除冒号和逗号。
@echo off
setlocal enabledelayedexpansion
REM Check to see if a service on the machine is stopped (it is always stopped by the time it gets here) before we move the files from the logging directory to a new one.
for /F "tokens=3 delims=: " %%H in ('sc \\REMOTESERVER query "SOME SERVICE NAME" ^| findstr " STATE"') do (
if /I "%%H" == "STOPPED" (
REM substring the date and time and then concat it together at the end to make the desired timestamp variable
set "CUR_YYYY=%date:~10,4%"
set "CUR_MM=%date:~4,2%"
set "CUR_DD=%date:~7,2%"
set "mytime=!time::=!"
set "mytime=!mytime:,=!"
set "TIMESTAMP=!CUR_YYYY!!CUR_MM!!CUR_DD!-!mytime!"
REM copy files from the servers source directory and then move the files to a newly created logging folder with a timestamp appened at the end
echo d | xcopy /f /y "\\REMOTE SERVER\src" "\\REMOTE SERVER\dest\Logging_!TIMESTAMP!" /E /I
REM delete the contents of the servers source directory to keep things nice and clean
pushd \\REMOTE SERVER\src && del . /F /Q popd
)
)
然而,为了解释你的问题,当你设置一个变量时,空格是变量的一部分。所以:
set variable = value
将导致变量带有尾随空格%variable %
而值带有前导空格<space>value
所以我们总是去掉空格,最好使用双引号来消除值后面可能出现的空格。例如:
set "variable=value"
这将创建%variable%
和value
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句