在 Azure 中自动为 NSG 创建 NSG 规则:键入 Get-AzNetworkSecurityGroup 中的错误

Automate NSG rule creation for NSGs within azure: Type error from Get-AzNetworkSecurityGroup

提问人:sam.solo.works 提问时间:2/9/2023 更新时间:2/9/2023 访问量:274

问:

我正在尝试编写一个脚本,以自动为我们的生产 NSG 创建 NSG 规则。我很确定我有一些东西接近工作,但我遇到的问题是命令返回一个字符串,所以我无法将其输入命令。Get-AZNetworkSecurityGroupAdd-AzNetworkSecurityRuleConfig

Import-Module Az.network
Connect-AzAccount
$tcpports = @(22,53,80,135,137,161,427,443,515,548,5060,5480,5985,5986,5989,9100,9443)
$udpports = @(53,161,427,515,548)
$solservers = #Server IP here
$file = Import-Csv C:\Users\temp\Downloads\AzureNSGs.csv

foreach ($NSG in $file){
$RGname=$NSG.'RESOURCE GROUP'
$nsgname=$NSG.NAME
$NSGObj = Get-AzNetworkSecurityGroup | Where-Object -Property Name -Like $RGname | Select-Object -Property Name
$name = "AllowSolarWinds"
    if($NSGObj){
    $name = $name + 1 
    $NSGObj | Add-AzNetworkSecurityRuleConfig -Name $name -NetworkSecurityGroup $NSGObj -Protocol Icmp -SourceAddressPrefix $solservers -DestinationPortRange "*" -Priority 555 
    $NSGObj | Set-AzNetworkSecurityGroup 
    }
}

每当我运行它时,我都会得到两种回报。它看起来要么成功运行,没有错误,但从未在 Azure 中创建该规则。或者 powershell 吐出以下错误之一。

Add-AzNetworkSecurityRuleConfig : Cannot bind argument to parameter 'NetworkSecurityGroup' because it is null.

Add-AzNetworkSecurityRuleConfig : Cannot bind parameter 'NetworkSecurityGroup'. Cannot convert the value of type "System.String" to type 
"Microsoft.Azure.Commands.Network.Models.PSNetworkSecurityGroup".
Azure PowerShell 对象 null azure-nsg

评论

0赞 Ross Lyons 2/9/2023
MS 文档通过将“Get-AzNetworkSecurityGroup”管道传递到“Add-AzNetworkSecurityRuleConfig”中来提供示例。看起来你在收集批次后筛选了“Get-AzNetworkSecurityGroup”,请尝试定义“-name”和“-resourceGroup”。它返回一个自定义 PS 对象,请参见此处: learn.microsoft.com/en-us/powershell/module/az.network/... -- 我刚刚注意到了这个问题。过滤后,您正在使用“Select-Object”。我相信这导致输出是一个字符串而不是预期的自定义对象。

答:

1赞 Imran 2/9/2023 #1

我试图在我的环境中重现相同的错误,如下所示:

enter image description here

要解决此错误,请尝试修改代码,如下所示:

Connect-AzAccount
Import-Module Az.network
$tcpports = @(22,53,80,135,137,161,427,443,515,548,5060,5480,5985,5986,5989,9100,9443)
$udpports = @(53,161,427,515,548)
$solservers = "112.121.61.196"
$file = Import-Csv C:\Users\v-khanimran\Downloads\AzureNSGs.csv

foreach ($NSG in $file){
$RGname=$NSG.RESOURCEGROUPNAME
$nsgname=$NSG.NAME
$NSGObj =Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname
#Get-AzNetworkSecurityGroup | Where-Object {$_.Name -Like $nsgname} | Select-Object -Property Name
$name = "AllowSolarWinds"
    if($NSGObj){
    $name = $name + 1 
    $NSGObj | Add-AzNetworkSecurityRuleConfig -Name $name  -Protocol Icmp -SourceAddressPrefix $solservers -DestinationPortRange  "*" -SourcePortRange "*" -DestinationAddressPrefix "*" -Priority 555 -Access Allow -Direction Inbound 
    
    $NSGObj | Set-AzNetworkSecurityGroup 
    }
}

输出:

enter image description here

在门户中,已成功添加 NSG 规则,如下所示:

enter image description here