问题
I am having a problem with the following script, which we wish to use as part of a login script in order to check if software has been installed, and if not, install it:
:STEP1
for /f "delims= " %%a in (C:\software-dist.txt) do (
if "%%a"=="Softwarename1" goto STEP2
)
\\server\share\software1.exe
echo Softwarename1 >> C:\software-dist.txt
:STEP2
for /f "delims= " %%a in (C:\software-dist.txt) do (
if "%%a"=="Software name 2" goto END
)
\\server\share\software2.exe /Q
echo Software name 2 >> C:\software-dist.txt
:END
The code is STEP1 works just fine - here the name of the software is a single word "Softwarename1". However, the code in STEP2 does not work - here the name of the software is written as 3 separate words "Software name 2" (a space between each word). Each time the script is run, the c:\software-dist.txt gets updated with another line of "Software name 2".
Any ideas what I am doing wrong?
回答1:
lc pointed out the problem in his comment, but didn't explicitly provide the obvious solution.
You are setting the token delimiter to a space. You need to disable the DELIMS option by using "DELIMS="
.
for /f "delims=" %%a in (C:\software-dist.txt) do ...
Also, your ECHO statement has an extra space at end that is causing the line not to match when you later test it in another run. If you remove the space then the 2 is treated as the handle for stderr. One fix is to add parentheses.
(echo Software name 2) >> C:\software-dist.txt
But there is a simpler and faster solution. You can use FINDSTR to determine if a particular line exists within a file.
:Step1
>nul findstr /xc:"Softwarename1" "C:\software-dist.txt" || (
"\\server\share\%%F"
>>"C:\software-dist.txt%" echo Softwarename1
)
:Step2
>nul findstr /xc:"Software name 2" "C:\software-dist.txt" || (
"\\server\share\%%F"
>>"C:\software-dist.txt%" echo Software name 2
)
The code is shorter and easier to maintain with the addition of a variable and a FOR loop.
set "file=C:\software-dist.txt"
for %%F in ("Softwarename1" "Software name 2") do (
>nul findstr /xc:%%F "%file%" || (
"\\server\share\%%~F"
(echo %%~F)>>"%file%"
)
)
来源:https://stackoverflow.com/questions/13125706/software-installation-script