Can't get a for loop to work in an if statement

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
mithril28
Posts: 7
Joined: 17 Jan 2018 16:54

Can't get a for loop to work in an if statement

#1 Post by mithril28 » 19 Jan 2018 14:43

I want to copy the contents of NewerFile to a log file if the time stamp of that file is different from OlderFile (this batch file will be run every 15 minutes, sometimes there are new files, sometimes not). I can get the following to work, but it's a waste of time to get the contents of the file only to find out that the time stamps match (meaning the files are the same and I've already saved off that data), but I can't get the (third) for loop to work inside the if statement. Any suggestions?

Code: Select all

@echo off
@SETLOCAL ENABLEDELAYEDEXPANSION
  
for %%a in (NewerFile.csv) do (
  set myfiledateLast=%%~ta
)
for %%a in (OlderFile.csv) do (
  set myfiledateNow=%%~ta
)
for /f "tokens=*" %%a in (NewerFile.csv) do ( 

if NOT !myfiledateLast! == !myfiledateNow! ( 
Copy %%a To Log File
)
)

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Can't get a for loop to work in an if statement

#2 Post by Squashman » 19 Jan 2018 16:34

There are spaces in your strings. Best practice is to ALWAYS use quotes to protect spaces and special characters.

Code: Select all

if NOT "!myfiledateLast!"=="!myfiledateNow!"

mithril28
Posts: 7
Joined: 17 Jan 2018 16:54

Re: Can't get a for loop to work in an if statement

#3 Post by mithril28 » 22 Jan 2018 09:05

I used the quotes, but I am still getting the error "The syntax of the command is incorrect.". I should have been more specific before, apologies.

Code: Select all

@echo off
@SETLOCAL ENABLEDELAYEDEXPANSION
  
for %%a in (NewerFile.csv) do (
  set myfiledateLast=%%~ta
)
for %%a in (OlderFile.csv) do (
  set myfiledateNow=%%~ta
)
if NOT "!myfiledateLast!" == "!myfiledateNow!" 
	( 
	for /f "tokens=*" %%a in (C:\Users\psnider\Documents\Stuff\MISCELLANEOUS\ArchiveAurora\Files_Helper\CDTNEW_Now.csv) do 	( 	
	echo %%a 	
	)
	else 
	(
	echo the same
	))

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Can't get a for loop to work in an if statement

#4 Post by Squashman » 22 Jan 2018 09:19

Why did you change the way you were using the parentheses?

Open up a cmd prompt and type: if /? . The help file clearly shows the proper syntax for using parentheses.

Post Reply