我需要一些有关 powershell 脚本的帮助,该脚本将 NSG 规则从一个订阅中的特定 NSG 克隆到另一个订阅中的 NSG。我有一个脚本,如果两个 NSG 都在同一个订阅中,则可以完成此操作,但如果它们在不同的订阅中,则无法完成。这是我有的。任何帮助都将不胜感激。
#name of NSG that you want to copy
$nsgOrigin = ""
#name new NSG
$nsgDestination = ""
#Resource Group Name of source NSG
$rgName = ""
#Resource Group Name when you want the new NSG placed
$rgNameDest = ""
$nsg = Get-AZNetworkSecurityGroup -Name $nsgOrigin -ResourceGroupName $rgName
$nsgRules = Get-AZNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg
$newNsg = Get-AZNetworkSecurityGroup -name $nsgDestination -ResourceGroupName $rgNameDest
foreach ($nsgRule in $nsgRules) {
$acl = @{Name = $nsgRule.Name; Protocol = $nsgRule.Protocol; SourcePortRange= $nsgRule.SourcePortRange; DestinationPortRange = $nsgRule.DestinationPortRange;Priority = $nsgRule.Priority;Direction = $nsgRule.Direction; Access = $nsgRule.Access; SourceApplicationSecurityGroup = $nsgRule.SourceApplicationSecurityGroups }
if ( $nsgRule.DestinationAddressPrefix.count -gt 0 ) {
$acl += @{DestinationAddressPrefix = $nsgRule.DestinationAddressPrefix }
}
if ( $nsgRule.SourceAddressPrefix.count -gt 0 ) {
$acl += @{SourceAddressPrefix = $nsgRule.SourceAddressPrefix }
}
if ( $nsgRule.SourceApplicationSecurityGroups.count -gt 0 ) {
$acl += @{SourceApplicationSecurityGroup = $nsgRule.SourceApplicationSecurityGroups }
}
if ( $nsgRule.DestinationApplicationSecurityGroups.count -gt 0 ) {
$acl += @{DestinationApplicationSecurityGroup = $nsgRule.DestinationApplicationSecurityGroups }
}
Add-AZNetworkSecurityRuleConfig -NetworkSecurityGroup $newNsg @acl
}
Set-AZNetworkSecurityGroup -NetworkSecurityGroup $newNsg
答案1
您只需像这样在源 nsg 之前和之后设置订阅上下文即可
设置 AzContext -SubscriptionName“SUBNAME”
$nsg = Get-AZNetworkSecurityGroup -名称 $nsgOrigin -资源组名称 $rg名称 $nsgRules = Get-AZNetworkSecurityRuleConfig -网络安全组 $nsg
设置 AzContext -SubscriptionName“SUBNAME”