Powershell split & trim 删除空格和逗号

Powershell split & trim to remove blanks and commas

我有 az 命令的输出,大约有 50 行,我想将每一行输入到 foreach 循环中以更改一些配置。问题是每一行都以逗号结尾,输出的开头和结尾都有一个 [ ] 字符。举个例子

[
  "/subscriptions/11c112-f823-4d5a-8615-8b96d08caf35/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/website-name-1",
  "/subscriptions/11c112-f823-4d5a-8615-8v9f9s9a9c9a/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/website-name-2",
  "/subscriptions/11c112-f823-4d5a-8615-8b96d08caf35/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/website-name-3"
]

我需要完成一个仅包含“ ”内文本的新行的列表,我尝试将其保存为变量并执行 $variable.split(",") 但这给了我没有逗号,每个之间有一个空行,我仍然有 [] 字符。有人可以帮我引导吗?

因为你有一个 Json 输出,你能做的最好的事情就是将你的 json 字符串转换为具有 ConvertFrom-JsonConvertTo-Json 的 PSCustom 对象表示功能。

这些将允许您将 Json 字符串转换为一个对象,轻松地进行所需的操作,而无需处理字符转义和直接处理字符串。

然后,当您结束后,如果您再次需要 Json,您可以轻松地将其转换回来。 ConvertTo-Json 将为您处理一切(字符转义、格式化等)。

这是一个例子。

$AzCommandOutput = 
@'
[
  "/subscriptions/11c112-f823-4d5a-8615-8b96d08caf35/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/website-name-1",
  "/subscriptions/11c112-f823-4d5a-8615-8v9f9s9a9c9a/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/website-name-2",
  "/subscriptions/11c112-f823-4d5a-8615-8b96d08caf35/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/website-name-3"
]
'@  | ConvertFrom-Json

$MyArray = [System.Collections.Generic.List[PSObject]]$AzCommandOutput


for ($i = 0; $i -lt $MyArray.Count; $i++) {
    # Do needed manipulation
    $MyArray[$i] = $MyArray[$i] -replace 'resource-group-name','My-Resource-Group'
}

#If ever you need the oputput in json format again... 
$NewOutput = $MyArray | ConvertTo-Json