Reputation: 125
I am new to batch scripting, coming from a linux environment, and have to write a couple of simple scripts here at work. I work in a manufacturing plant and when a product passes a test it saves a test certificate onto the LAN. We have dozens of products, but management wants to be able to have a script running that at any given point in the day we can see how many of each product has been built. My approach to this is navigating to where these test certificates are saved and seeing which ones were modified today.
So the following script works for almost all of the products, but or some reason on two of them it doesn't write the count to the file that I specified.
@echo off
setlocal
set count=0
cd /D T:/"Product Name"/"Test Certificates"
for /f %%i in ('forfiles -m *.txt -d 0 /c "cmd /c echo @FILE"') do @call set /a count+=1
echo %count%>J:\units_built\currently_built_productA.txt
endlocal
I tried taking the write command out to see if the count variable was being set and it is. So for some reason the write isn't working. It is creating an empty text file even though count is an integer... I have the exact same code working in various other examples but for some reason two won't. Please help! Thank you
Upvotes: 0
Views: 5558
Reputation: 312
Might it be possible that this is because really low numbers + ">", like 1> for example, will be interpreted as a separate command in batch?
Writing Numbers to a text file - batch file
I'm new to this, but maybe you could try writing (like this link suggests)
>mytextfile.txt echo %count%
instead.
Upvotes: 1
Reputation: 41234
The issue is probably the redirection - which fails when some numerals are immediately prior to a >
character such as 1>
and 2>
(it eats the number). This will solve that problem by using the redirection at the front of the line:
>J:\units_built\currently_built_productA.txt echo %count%
Upvotes: 0
Reputation: 130839
I'm assuming currently_built_productA
is a dynamic value. Your code will not write to the correct location if the value has spaces. For example, echo Hello world>A B.txt
will write to a file named simply A
. The solution is to put quotes around the output file name: echo Hello world>"A B.txt"
You can greatly simplify your script.
@echo off
setlocal
set "product=SomeProduct"
forfiles /p "T:\%product%\Test Certificates" /m *.txt -d 0|find /c """" >"J:\units_built\%someProduct%.txt"
The output of FORFILES is piped to a FIND command that counts the number of lines that contain a quote. The search string must be enclosed in quotes, and quote literals must be escaped by doubling.
Note that escaping a quote as ""
is a feature of the FIND command. Most batch commands escape quotes using ^"
.
UPDATE
Wouter's answer identifies another likely problem with the OP's original code. The simplified code above will not suffer that problem.
Upvotes: 2