Azure 正在获取NSG和相应子网或NIC的列表
提前谢谢 我正在编写Azure PowerShell脚本,该脚本将获取所有NSG,并查找它是否连接到NIC或子网,并在CSV中给出相同的名称 我一直在解析NSG,因为它有属性SubnetsText,它以下面的格式输出数据。我试图用substring方法来解析它,但它不起作用。以前有人试过吗Azure 正在获取NSG和相应子网或NIC的列表,azure,azure-powershell,network-security-groups,Azure,Azure Powershell,Network Security Groups,提前谢谢 我正在编写Azure PowerShell脚本,该脚本将获取所有NSG,并查找它是否连接到NIC或子网,并在CSV中给出相同的名称 我一直在解析NSG,因为它有属性SubnetsText,它以下面的格式输出数据。我试图用substring方法来解析它,但它不起作用。以前有人试过吗 [ { "TapConfigurations": [], "HostedWorkloads": [], "Id": "/subscriptions/xxxx-xxxx-xxx-xx
[
{
"TapConfigurations": [],
"HostedWorkloads": [],
"Id": "/subscriptions/xxxx-xxxx-xxx-xxx-xxxxxx/resourceGroups/vm-test-group/providers/Microsoft.Network/networkInterfaces/testvm1VMNic"
}
]
下面是cmdlet
$nsg = Get-AzureRmNetworkSecurityGroup -Name testvm1NSG -ResourceGroupName vm-test-group
$nsg.SubnetsText.ToString().Substring(lastindexof('/')+1)
你可以这样做:
$nsg.Subnets.Id.Split('/')[-1]
这将拆分
/
上的字符串,并从该操作中获取最后一项,即NIC名称。您应该可以使用Newtonsoft JSON执行此操作(理论上,您应该可以对get-AzureRmNetworkSecurityGroup的整个输出执行此操作)
为了尝试这一点,我首先将您的SubnetsText放入一个字符串中
string nsg =
"[{\"TapConfigurations\":[],\"HostedWorkloads\":[],\"Id\":\"/subscriptions/xxxx-xxxx-xxx-xxx-xxxxxx/resourceGroups/vm-test-group/providers/Microsoft.Network/networkInterfaces/testvm1VMNic\"}]";
接下来,我创建了一个名为X的新动态,并将JSON解析为JArray
dynamic x = JArray.Parse(nsg);
我创建了一个名为id的新字符串,并获取id的值。我还创建了一个名为idList的新列表
string id = x[0].Id.ToString();
var idList = new List<string>();
将x[0].Id写入控制台时,我得到:
/订阅/xxxx-xxxx-xxx-xxxxxx/resourceGroups/vm测试组/providers/Microsoft.Network/networkInterfaces/testvm1VMNic
当我从列表中得到我想要的特定值时(在本例中,我想要接口名,它是第8项),我将idList[8]写入控制台并得到:
testvm1VMNic
注意:这是在c#中(因为这是我使用类似工具的地方),但是如果您可以访问Powershell库,您应该能够在Powershell中以类似的方式执行此操作Hi-Gleb,我将在下面的输出PS c:\WINDOWS\system32>$nsg.SubnetsText.ToString().Split('/')[-1]default”,“ServiceAssociationLink:[]}]我只想要defaultyeah,抱歉,不知道我在想什么,试试这个;)谢谢Gleb的及时回复:)(不要为这个愚蠢的错误说抱歉)谢谢,但我正在开发简单的powershell,并将尝试这个更复杂的解决方案
idList = id.Split('/').ToList();
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