提问人:sam.solo.works 提问时间:2/9/2023 更新时间:2/9/2023 访问量:274
在 Azure 中自动为 NSG 创建 NSG 规则:键入 Get-AzNetworkSecurityGroup 中的错误
Automate NSG rule creation for NSGs within azure: Type error from Get-AzNetworkSecurityGroup
问:
我正在尝试编写一个脚本,以自动为我们的生产 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".
答:
1赞
Imran
2/9/2023
#1
我试图在我的环境中重现相同的错误,如下所示:
要解决此错误,请尝试修改代码,如下所示:
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 规则,如下所示:
评论