windows 从文件中读取值并将其分配给批处理脚本中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2264477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:56:02  来源:igfitidea点击:

Reading values from file and assigning it to variable in batch script

windowsbatch-filecmd

提问by Shekhar

I want to read the file which contains the value of some variables which are used in my batch script. I have created a property file with format

我想读取包含批处理脚本中使用的某些变量值的文件。我创建了一个格式的属性文件

key=key_value
key=key_value

Now, I want to set environment variable's name as key and its value as key_value How can I assign?

现在,我想将环境变量的名称设置为键,将其值设置为 key_value 如何分配?

I have read the file but cannot separate the string "key=key_value" into two strings. Thanks in advance.

我已阅读该文件,但无法将字符串“key=key_value”分成两个字符串。提前致谢。

采纳答案by John Knoeller

With the FOR command you can turn your key/value file from this

使用 FOR 命令,您可以从这里转换您的键/值文件

KEY1=value
KEY2=value

into this

进入这个

SET KEY1=value
SET KEY2=value

which you can then invoke as a batch file to set all of the keys as environment variables. this only works if all of the keys are unique, but from your question it sounds like they are.

然后您可以将其作为批处理文件调用以将所有键设置为环境变量。这仅在所有键都是唯一的情况下才有效,但从您的问题来看,它们似乎是唯一的。

save this as a batch file

将此保存为批处理文件

@echo off
echo rem generated from keyvalue.txt > keyvalue.bat
for /F "tokens=*" %%I in (keyvalue.txt) do @echo set %%I >> keyvalue.bat

call keyvalue.bat

This .bat code assumes that your key/value file is keyvalue.txt and that there are no lines other than blank lines or key=value pairs.

此 .bat 代码假定您的键/值文件是 keyvalue.txt 并且除了空行或键=值对之外没有其他行。