【问题标题】:Getting list of NSG and corresponding Subnet or NIC获取 NSG 列表和对应的子网或网卡
【发布时间】:2019-11-03 06:21:20
【问题描述】:

提前致谢。

我正在研究 Azure PowerShell 脚本,它将获取所有 NSG 并查找它是否附加到 NIC 或子网,并在 CSV 中给出相同的名称。

我一直在解析 NSG,因为它具有属性 SubnetsText,它以以下格式输出数据。我正在尝试使用 substring 方法解析它,但它不起作用。以前有人试过吗?

[
  {
    "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)

【问题讨论】:

    标签: azure azure-powershell network-security-groups


    【解决方案1】:

    你可以这样做:

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

    这将拆分 / 上的字符串并从该操作中获取最后一项,即 NIC 名称。

    【讨论】:

    • 嗨 Gleb,我的输出低于 PS C:\WINDOWS\system32> $nsg.SubnetsText.ToString().Split('/')[-1] default", "ServiceAssociationLinks" : [] } ] 我只想要默认
    • 是的,抱歉,不知道我在想什么,试试这个 ;)
    • 感谢 Gleb 的及时回复 :) (不要为这个愚蠢的错误道歉)
    【解决方案2】:

    您应该能够使用 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>();
    

    最后,我使用 .Split() 和 .ToList() 用 id 的值填充了 idList

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

    当写出 x[0].Id 到控制台时,我得到:

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

    当我从列表中获得我想要的特定值时(在这种情况下,我想要接口名称,即第 8 项)我将 idList[8] 写入控制台并获取:

    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
    

    注意:这是在 c# 中(因为这是我在使用类似工具的地方)但是如果您可以访问 Powershell 库,您应该能够在 Powershell 中以类似的方式进行操作

    【讨论】:

    • 谢谢,但我正在研究简单的 powershell,并将尝试这个更复杂的解决方案
    猜你喜欢
    • 2019-04-30
    • 2021-04-18
    • 2015-12-06
    • 2022-01-24
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多