在powershell中将其中一个成员作为JSON的数组传递

在powershell中将其中一个成员作为JSON的数组传递,json,powershell,powershell-4.0,Json,Powershell,Powershell 4.0,下面是一个小的Powershell代码片段: $users = New-Object System.Collections.ArrayList $userAsJson = ' { "name" : "abc", "companies" : ["facebook", "google"] }' $user = $userAsJson | ConvertFrom-Json $null = $users.Add($user) $users | ConvertTo-Json -Depth

下面是一个小的Powershell代码片段:

$users = New-Object System.Collections.ArrayList
$userAsJson = '
{
    "name" : "abc",
    "companies" : ["facebook", "google"]
}'
$user = $userAsJson | ConvertFrom-Json
$null = $users.Add($user)
$users | ConvertTo-Json -Depth 5
它为我提供了以下预期输出:

{
    "name":  "abc",
    "companies":  [
                      "facebook",
                      "google"
                  ]
}
现在,我正在动态地创建公司列表。我尝试了我能想到的所有可能的事情。以下是我尝试过的:

$company = New-Object System.Collections.ArrayList
$null = $company.Add('facebook')
$null = $company.Add('google')
$b = $company.ToArray()

$users = New-Object System.Collections.ArrayList
$userAsJson = '
{
    "name" : "abc",
    "companies" : $b
}'

$user = $userAsJson | ConvertFrom-Json
$null = $users.Add($user)

$users | ConvertTo-Json -Depth 5

有人能告诉我实现这一目标的最佳方法吗?

PowerShell的优势在于一直呆在领域对象中,直到与外部世界接口的时候,例如在写入文件或创建这些对象的字符串表示时

在您的情况下,这意味着:

# Array of companies; statically constructed here, but creating it
# dynamically works just as well.
$company = (
 'facebook',
 'google'
)

# Initialize the output collection.
# Note: Creating a [System.Collections.ArrayList] instance is
#       advisable for building up *large* arrays *incrementally*.
#       For smallish arrays, using regular PowerShell arrays will do; e.g.:
#         $users = @() # initialize array
#         $users += ... # append to array, but be aware that a *new* array 
#                         is created behind the scenes every time.
$users = New-Object System.Collections.ArrayList

# Add a user based on the $company array defined above as
# a [pscustomobject]
$null = $users.Add(
  [pscustomobject] @{
    name = 'abc'
    companies = $company
  }
)

# After all users have been added *as objects*, convert them to JSON.
$users | ConvertTo-Json -Depth 5
上述结果(基于已添加的单个对象;如果添加更多对象,将输出JSON数组):


$user=@{name='abc'}$user.companys='facebook'、'google'$用户| convertto json
-为什么要尝试将arraylist嵌入到字符串中,然后将其从字符串转换回powershell?这是干什么用的?我正在把公司名单整理成一个循环。它应该为每个用户执行。为了简单起见,我刚刚删除了循环。如何动态提供公司列表?提前谢谢!
{
  "name": "abc",
  "companies": [
    "facebook",
    "google"
  ]
}