2

Thanks in advance.

I'm working on Azure PowerShell Script which will get all the NSG and finds whether it is attached to NIC or Subnet and give the name of the same in CSV.

I'm stuck in parsing the NSG as it has property SubnetsText which outputs the data in below format. I'm trying to parse it using substring method but it did not work. Anybody tried this before?

[
  {
    "TapConfigurations": [],
    "HostedWorkloads": [],
    "Id": "/subscriptions/xxxx-xxxx-xxx-xxx-xxxxxx/resourceGroups/vm-test-group/providers/Microsoft.Network/networkInterfaces/testvm1VMNic"
  }
]

Below is the cmdlet

$nsg = Get-AzureRmNetworkSecurityGroup -Name  testvm1NSG -ResourceGroupName vm-test-group

$nsg.SubnetsText.ToString().Substring(lastindexof('/')+1)

2 Answers2

2

you could just do this:

$nsg.Subnets.Id.Split('/')[-1]

this would split the string on / and get the last item from that operation, which would be the NIC name.

4c74356b41
  • 69,186
  • 6
  • 100
  • 141
0

You should be able to do this with Newtonsoft JSON (In Theory you should be able to do this for the whole output from Get-AzureRmNetworkSecurityGroup)

To try this I first took your SubnetsText into a string.

 string nsg =
            "[{\"TapConfigurations\":[],\"HostedWorkloads\":[],\"Id\":\"/subscriptions/xxxx-xxxx-xxx-xxx-xxxxxx/resourceGroups/vm-test-group/providers/Microsoft.Network/networkInterfaces/testvm1VMNic\"}]";

Next, I Created a new dynamic called X and parsed the JSON into it as a JArray.

dynamic x = JArray.Parse(nsg);

I created a new string called id and took the value of Id. I also created a new list called idList

string id = x[0].Id.ToString();
var idList = new List<string>();

Lastly, I populated the idList with the values of id using .Split() and .ToList()

idList = id.Split('/').ToList();

When writing out x[0].Id to console I get:

/subscriptions/xxxx-xxxx-xxx-xxx-xxxxxx/resourceGroups/vm-test-group/providers/Microsoft.Network/networkInterfaces/testvm1VMNic

And when I get the specific value I want from the list (In this case I want the Interface name, which is the 8th item) I write idList[8] to console and get:

testvm1VMNic

        Console.WriteLine(x[0].Id);
        Console.WriteLine(idList[1]); // subscriptions
        Console.WriteLine(idList[2]); // xxxx-xxxx-xxx-xxx-xxxxxx
        Console.WriteLine(idList[3]); // resourceGroups
        Console.WriteLine(idList[4]); // vm-test-group
        Console.WriteLine(idList[5]); // providers
        Console.WriteLine(idList[6]); // Microsoft.Network
        Console.WriteLine(idList[7]); // networkInterfaces
        Console.WriteLine(idList[8]); // testvm1VMNic

Note: This is in c# (As this is where I was working on a similar tool) but you should be able to do it in a similar way in Powershell if you can access the Powershell Gallery

CloudTheWolf
  • 334
  • 2
  • 10