azure - Azure powershell - 如何拉
问题描述
我有一个 Azure powershell 脚本,它提取一个 XML 文件,然后通过“foreach”循环运行这些值。
我在 Azure 存储中有一个具有以下格式 (XML) 的 blob 文件 -
<?xml version="1.0"?>
<Root>
<PublicSubnets>
<Subnet>192.168.1.0/24</Subnet>
<Subnet>192.168.50.0/24</Subnet>
<Subnet>10.82.19.5/24</Subnet>
<Subnet>10.1.1.0/16</Subnet>
<Subnet>172.16.15.0/16</Subnet>
</PublicSubnets>
<Descrip>
<Description>"This is the description"</Description>
</Descrip>
</Root>
这个想法是让一个 azure powershell 脚本循环遍历 XML 并为每个脚本创建一个网络安全组条目。 那部分工作得很好。
我想要做的不是摄取 XML 文件,而是希望它是一个包含所有子网值的 Json。
这是当前脚本(请注意,$nsgname 和 $resourcegroupname 由用户输入,对于网络安全组,该脚本随后将为 XML 文件中的每个子网创建 NSG 条目)
$Url = "https://theteststorage.blob.core.windows.net/params/SubnetParams.xml?st=2018-10-25T19andrestoftheURL"
$Subnets = @()
[xml]$xml = Invoke-WebRequest $Url -UseBasicParsing | Select-Object -Expand Content
$counter=0
foreach ($subnet in $xml.Root.PublicSubnets.Subnet)
{
$counter++
Write-Output "Counter is at $counter and subnet is $subnet"
}
这应该打印出来:计数器在 1,子网是 192.168.1.0/24 计数器在 2,子网是 192.168.50.0/24
我将如何去做,但不是 XML,而是 Json
解决方案
您需要做的是将 json 文件内容下载为字符串,然后使用ConvertFrom-Json
.
请按照以下代码进行操作:
$url="https://xxx.blob.core.windows.net/t1s/test.json"
$subnets=@()
$web_client = New-Object System.Net.WebClient
$download_json = $web_client.DownloadString($url)
#convert the download string to a PowerShell object
$json = $download_json | ConvertFrom-Json
$counter=0
foreach($subnet in $json.Root.PublicSubnets.Subnet)
{
$counter++
Write-Output "Counter is at $counter and subnet is $subnet"
}
test.json 文件:
{
"Root": {
"PublicSubnets": {
"Subnet": [
"192.168.1.0/24",
"192.168.50.0/24",
"10.82.19.5/24",
"10.1.1.0/16",
"172.16.15.0/16"
]
},
"Descrip": { "Description": "\"This is the description\"" }
}
}
更新:
或者您可以使用Invoke-RestMethod -Uri $url
,它将自动解析对 PSObject 的 json 响应:
推荐阅读
- angular - Angular 9 无法使用 AWS S3 和 Cloudfront 加载模块脚本
- javascript - Thymeleaf 页面如何检查用户是否登录
- javascript - TypeError:“RequestInitializerDict”上“headers”字段的类型不正确:提供的值不是“variant”类型
- javascript - 无法 console.log 分配给获取的 API 的变量是否正常?
- linux - awk regx 不适用于文件中的字符串
- amazon-ec2 - cloud-init:延迟 disk_setup 和 fs_setup
- javascript - Webpack 无法加载高阶组件?
- scala - 关于 spark scala Array() 的说明
- python - 递归中的变量位置
- c - Strok 没有正确标记单词