自动为Azure中的NSG创建NSG规则:获取AzNetworkSecurityGroup时出现类型错误

jmp7cifd  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(152)

我正在尝试编写一个脚本,以便自动为生产NSG创建NSG规则。我确信我已经有了一些工作,但我遇到的问题是Get-AZNetworkSecurityGroup命令返回一个字符串,因此我无法将其输入Add-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".
2ledvvac

2ledvvac1#

我尝试在我的环境中重现相同的错误,但得到了如下相同的错误:

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

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 
    }
}

输出:

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

相关问题