如何通过文件本身更改BATCH文件中的变量值?

时间:2015-04-12 12:28:14

标签: batch-file

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

我缩小的BATCH文件(“Some 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值)。

另一件事是没有复制空行。

任何解决方案?

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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