首页 > 解决方案 > 对列表使用 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 中显示它,但说我做了并且等于. 然后我会说类似test1test2env = getEnvironmentVariable(test)test1for i in $rawData.env return getEnvironmentVariable(i)

我非常想要另一个列表或新的 json 对象,其中包含我们从原始 json 对象获得的假定环境变量的值。

有没有办法在powershell中做到这一点?如果有人可以提供帮助,那将有很大帮助。如果我有什么不清楚的地方,我很抱歉。谢谢

(编辑)我看到那$rawData.Get-ChildItem Env:test行不通。有没有人为了从 json 文件中获取正确的列表而写这样的东西?

像这样设置一个新变量$var1 = Get-ChildItem Env.tool并且这样做$rawData.$test.value也没有效果。

标签: powershellfor-loop

解决方案


# 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"
  }
]

推荐阅读