Create a bat file with variables from another bat file

那年仲夏 提交于 2020-03-18 09:19:32

问题


I want to create a bat file with set variables from another bat file. This is for a startup .bat file that maps network drives and copies some files to the local computer and looks at the system services that needs to run.

It also needs to create a log file every time the logon .bat file runs. Here is a sample what I have done.

ECHO set SERVER IP=>>"V:\GENESIS\GENESIS INSTALL FILES\GenesisLogonUser.bat"
ECHO set DRIVE1=V>>"V:\GENESIS\GENESIS INSTALL FILES\GenesisLogonUser.bat"
ECHO set MAPDRIVE1=\\%SERVER IP%\v /P:Yes>>"V:\GENESIS\GENESIS INSTALL FILES\GenesisLogonUser.bat"
ECHO net use %DRIVE1%: %MAPDRIVE1% >>"%userprofile%\Documents\scripts\logonlog.txt">>"V:\GENESIS\GENESIS INSTALL FILES\GenesisLogonUser.bat"

回答1:


You need to escape percent expansion of the variables. This can be done by doubling each % sign in a batch script:

set "VAR=Value"
echo %%VAR%%

This will echo:

%VAR%

Note that this does not work directly in the console window; you need to do it like this instead:

>set "VAR=Value"

>echo ^%VAR^%
%VAR%

So to apply this to your script, it looks like this (I excluded %USERPROFILE% from the escaping as I do not know how you like it; of course you could write %%USERPROFILE%% instead as well):

(
    ECHO set "SERVER IP="
    ECHO set "DRIVE1=V"
    ECHO set "MAPDRIVE1=\\%%SERVER IP%%\v /P:Yes"
    ECHO net use %%DRIVE1%%: %%MAPDRIVE1%%^>^>"%USERPROFILE%\Documents\scripts\logonlog.txt"
) > "V:\GENESIS\GENESIS INSTALL FILES\GenesisLogonUser.bat"

Since there is some redirection in the echoed text, this needs to be escaped like ^>^>.

I also put all ECHO commands within parentheses, which requires a single redirection operation only; this improves legibility and performance.

In addition, I improved the set syntax so that the entire assignment expression is placed in between a pair of quotation marks, which make it robust against special characters (the quotes do not become part of the value).



来源:https://stackoverflow.com/questions/39595754/create-a-bat-file-with-variables-from-another-bat-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!