Reputation: 321
I need to write a code, that replaces the whitespace of the timestring of the %test%
variable, and output it in the format foo01_08_2018-06_07_47.war
.
The code below returns the correct string, if isolated from the IF statement, however, this code returns a syntax error somewhere. Im using windows 10 and the batch file is supposed to work on the Windows Server 2016 OS.
@echo off
SET test=" 6:07:47,43"
IF "%test%"=="%test: =%" (
echo foo%date:~0,2%_%date:~3,2%_%date:~6,6%-0%time:~1,1%_%time:~3,2%_%time:~6,2%.war
) ELSE (
echo foo%date:~0,2%_%date:~3,2%_%date:~6,6%-%time:~0,2%_%time:~3,2%_%time:~6,2%.war
)
pause
Any Idea about what is wrong with this IF statement? I've tried countless solutions offered by stackoverflow, all of them seem to be either obsolete or just dont work in my case.
Upvotes: 0
Views: 379
Reputation: 14290
You should consider using a method to get the date and time in a format that is consistent. In a batch file you can use WMIC and Powershell to do this.
Using WMIC the output will always be in this format: YYYYYMMDDhhmmss
for /f "tokens=2 delims==." %%G in ('wmic OS Get localdatetime /value') do set "dt=%%G"
In Powershell you can control the the output format. You can reorder any of the date and time values and use whatever separator you want.
FOR /F "usebackq delims=" %%G IN (`powershell "(Get-Date).ToString('yyyy-MM-dd-hh-mm-ss')"`) DO set dt=%%G
Upvotes: 1
Reputation: 66
Your if statement is comparing "" 6:07:47,43""
and ""6:07:47,43""
. The syntax error is because of the double "
, once from the IF "%test%"=="%test: =%"
and once from the variable value " 6:07:47,43"
.
Just remove them from the set statement or the if statement. The if statement itself does not need the quotes so if %test%==%test: =%
would be fine. If %test%
is empty the if statement will have another syntax error (comparing nothing) so setting the variable without quotes is recommend.
SET test= 6:07:47,43
An undocumented feature is that you can set the set statement in "
. This will result in the same variable value but is save for &
and other special characters in the value.
SET "test= 6:07:47,43"
Upvotes: 4
Reputation: 5308
The correct syntax for SET with quotes is: SET "foo=bar"
instead of SET foo="bar"
Changing the second line to
SET "test= 6:07:47,43"
seems to do the trick
Upvotes: 2