2015-04-12 83 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_代碼,因此 - 我接受了你的答案。再次感謝。 –

相關問題