2015-04-12 79 views
0

我正在寻找很长时间现在回答这个问题,从http://www.dostips.com/DtTutoPersistency.phphttp://ss64.com/nt/for_cmd.html网站学到了很好的窍门,但仍然 - 没有解决我遇到的问题: 我有一个BATCH文件,其中我测试了特定文件夹(SendTo文件夹)的存在。如果我无法通过脚本找到它 - 我希望用户输入该文件夹的路径 - 并且将结果保留在BATCH文件中。如何通过文件本身更改BATCH文件中的变量值?

我缩小批处理文件(“有些file.bat”)看起来像:

@echo off 

REM SomeNonsense 

:: Win7/Vista 
IF EXIST %APPDATA%\Microsoft\Windows\SendTo\NUL (
REM Do something 
GOTO :EOF 
) 

:: WinXP 
IF EXIST %USERPROFILE%\SendTo\NUL (
REM Do something 
GOTO :EOF 
) 

:: Else 
SET SendPath= 
SET /P SendP="Please enter the path to the SendTo Folder:> " 
IF EXIST %TMP%\SendPath.txt DEL %TMP%\SendPath.txt 
FOR /F "usebackq TOKENS=* DELIMS=" %%A in ("%~0") DO (
ECHO %%A>>%TMP%\SendPath.txt 
REM Later I want to change the value of SendPath with SendP, 
REM And swap the file back to the original name 
) 

我的问题,现在是该文件的实际行被解释,我只想复制文本本身为临时文件(不使用COPY,因为我想逐行拷贝以改变SendPath值)。

另一件事是空行不被复制。

任何解决方案?

回答

1

这做你想要什么:

@echo off 

rem Your previous Win7/Vista, WinXP testings here... 

:: Else 
call :defineSendPath 

if defined SendPath goto continue 

SET /P "SendPath=Please enter the path to the SendTo Folder:> " 
rem Store the SendPath given into this Batch file: 
echo set "SendPath=%SendPath%" >> "%~F0" 

:continue 

rem Place the rest of the Batch file here... 


goto :EOF 

rem Be sure that the following line is the last one in this file 

:defineSendPath 
1

作为概念

@echo off 
    setlocal enableextensions disabledelayedexpansion 

    call :persist.read 

    if not defined savedValue (
     set /p "savedValue=Value to save:" && (call :persist.write savedValue) || (
      echo Value not set, process will end 
      exit /b 1 
     ) 
    ) 

    echo Saved value = [%savedValue%] 

    goto :eof 

:persist.read 
    for /f "tokens=1,* delims=:" %%a in (' 
     findstr /l /b /c:":::persist:::" "%~f0" 
    ') do set "%%~b" 
    goto :eof 

:persist.write varName 
    if "%~1"=="" goto :eof 
    for %%a in ("%temp%\%~nx0.%random%%random%%random%.tmp") do (
     findstr /l /v /b /c:":::persist::: %~1=" "%~f0" > "%%~fa" 
     >"%~f0" (
      type "%%~fa" 
      echo(
      setlocal enabledelayedexpansion 
      echo(:::persist::: %~1=!%~1! 
      endlocal 
     ) 
     del /q "%%~fa" 
    ) 
    goto :eof 

与编辑本身运行时是它保持在何处被执行的命令文件中的字符位置批处理文件问题的证明。您只能在当前正在执行的行中进行更改,这也会产生其他问题。因此,最安全(不是更优雅也最快速)的通用方法可能是将数据作为注释写在文件末尾。

+0

即使寿@ Aacini的回答更为直接 - 我仍然接受你,因为它是比较一般,并用的情况下交易,当你想超过一个持久的变量。谢谢你们两位,伙计们 –

+0

在我的解决方案中,你可以存储_several_变量,并将它们放在几行连续的行中,用一个'call:defineVariables'行定义它们,然后通过'if defined thisVar ...' 。当然,你可以接受任何你想要的答案,但是给出的理由对我来说听起来很奇怪......(什么“更一般”意味着什么?) – Aacini

+0

显然,你是对的 - 我**使用你的代码来检查几个变量成功,我的不好。 “更一般”我的意思是说这个解决方案并不是专门为我量身定做的,但是在一天结束时 - 简单的胜利 - 这意味着我使用了_your_代码,因此 - 我接受了你的答案。再次感谢。 –

相关问题