Reputation: 315
I have an Azure powershell script that's pulling an XML file and then running the values through a 'foreach' loop.
I have a blob file in Azure storage with the following format (XML) -
<?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>
The idea is for an azure powershell script to loop through the XML and create a network security group entry for each of them. That part works just fine.
What i'm trying to do is instead of ingesting a XML file, I want it to be a Json with all the subnet values.
Here's the current script (note that $nsgname and $resourcegroupname are entered by the user, for a network security group that the script will then create NSG entries for each subnet in the XML file)
$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"
}
This should print out: Counter is at 1 and subnet is 192.168.1.0/24 Counter is at 2 and subnet is 192.168.50.0/24
How would I go about doing that but instead of XML, it would be Json
Upvotes: 1
Views: 187
Reputation: 29940
What you need to do is that download the json file content as string and then convert it to Powershell object using ConvertFrom-Json
.
Please follow the code as below:
$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"
}
the test.json file:
{
"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\"" }
}
}
Update:
Or you can use Invoke-RestMethod -Uri $url
, which will parse the json response to PSObject automatically:
Upvotes: 1