powershell - 对列表使用 for 循环并将元素设置为环境变量,然后获取值
问题描述
我根本不熟悉powershell,只需要几个命令。我希望有人可以帮助我。我有一个名为的 json 文件optionsConfig.json
,内容如下,
{
"test1": ["options_size", "options_connection", "options_object"],
"test2":["options_customArgs", "options_noUDP", "options_noName"]
}
在我的 powershell 文件中,到目前为止我只有一行,这是获取 json 文件的内容。
$rawData = Get-Content -Raw -Path "optionsConfig.json" | ConvertFrom-Json
我曾计划在我的系统上使用一个名为or的环境变量,然后我test
将在 json 文件中的关联值中查看列表的元素。使用列表中的这些元素,我会假设它们也是环境变量,我想获取它们的值。(在这里,python 中的列表理解将是完美的)。我是一个 python 人,所以我不太确定如何在 powershell 中显示它,但说我做了并且等于. 然后我会说类似test1
test2
env = getEnvironmentVariable(test)
test1
for i in $rawData.env
return getEnvironmentVariable(i)
我非常想要另一个列表或新的 json 对象,其中包含我们从原始 json 对象获得的假定环境变量的值。
有没有办法在powershell中做到这一点?如果有人可以提供帮助,那将有很大帮助。如果我有什么不清楚的地方,我很抱歉。谢谢
(编辑)我看到那$rawData.Get-ChildItem Env:test
行不通。有没有人为了从 json 文件中获取正确的列表而写这样的东西?
像这样设置一个新变量$var1 = Get-ChildItem Env.tool
并且这样做$rawData.$test.value
也没有效果。
解决方案
# Sample values: make environment variable 'test' ($env:test)
# point to property 'test1'
$env:test = 'test1'
# Provide sample values for the environment-variable names listed
# in the 'test1' property.
$env:options_size = 'size1'
$env:options_connection = 'conn1'
$env:options_object = 'obj1'
# Read the JSON file into a custom object.
$configObj = Get-Content -Raw optionsConfig.json | ConvertFrom-Json
# Retrieve the environment variables whose
# names are listed in the $env:test property ('test1' in this example),
# as name-value pairs.
Get-Item -Path env:* -Include $configObj.$env:test
上面产生了一个实例数组,[System.Collections.DictionaryEntry]
每个实例代表一个环境变量的名称和值:
Name Value
---- -----
options_connection conn1
options_object obj1
options_size size1
要将上述内容转换为 JSON:
Get-Item -Path env:* -Include $configObj.$env:test |
Select-Object Name, Value | ConvertTo-Json
注意:看似多余的Select-Object
调用对于剥离 PowerShell 在幕后添加的其他属性是必要的,否则这些属性会显示在生成的 JSON 中。
如果您想重命名Select-Object
生成的 JSON 中的属性,无论如何您都需要使用计算属性。
这产生:
[
{
"Name": "options_connection",
"Value": "conn1"
},
{
"Name": "options_object",
"Value": "obj1"
},
{
"Name": "options_size",
"Value": "size1"
}
]
推荐阅读
- amazon-dynamodb - 使用值列表查询 DynamoDB GSI
- javascript - 反应 ref 以通过呈现为 this.props.children 的子级
- java-8 - 缓存 Java 8 流
- c++ - 无法检测 T::value() 使用 auto 参数化 true_type
- ios - aws Rekognition 未在 iOS 上初始化
- c# - 如何使用泛型将两个函数组合成一个函数?
- python - 获取 zip 文件的详细信息 - 而不是从其内容中获取
- python - 在python中检查两个字符是否相等
- reactjs - firebase中的多条记录,在回调函数中重用之前生成的id
- asp.net - 将所有 CheckBoxList 数据插入数据库