我有一个用于查找所有入站的脚本,允许 Azure NSG 中的规则是任何源。它正在完成他的工作,但只需要大量时间来迭代 Azure 中每个可用 NSG 中的每个规则。
问题是有什么方法可以优化它,所以它可以更快地工作吗?谢谢!
function nsg {
# List of default rules which are skipped
$array =
'Default rules'
# Get all RG with NSG
$RGS = (Get-AzureRmResource -ODataQuery "`$filter=resourcetype eq 'Microsoft.Network/networkSecurityGroups'").ResourceGroupName | Sort-Object -Unique
foreach ($RG in $RGS) {
# List of all NSG names
$NSG_Names = (Get-AzureRmNetworkSecurityGroup -ResourceGroupName $RG).Name
# Get NSG rules
foreach ($NSG_Name in $NSG_Names){
$Rules = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig | Select-Object -ExpandProperty Name
# Check if rule is not default
foreach ($Rule in $Rules){
if ($array.contains($Rule)){
Write-Verbose "$Rule excluded because it is default!"
}
else {
Write-Verbose "$NSG_Name - $Rule"
#$DestinationAddressPrefix = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty DestinationAddressPrefix
$DestinationPortRange = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty DestinationPortRange
$SourceAddrPref = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty SourceAddressPrefix
$SourcePortRange = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty SourcePortRange
$Access = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty Access
$Direction = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty Direction
# Chek rule for every criterion, access type, etc.
if ($Direction -eq "Inbound" -and $SourceAddrPref -eq "*" -and $Access -eq "Allow"){ #-and $DestinationAddressPrefix -eq "*" -and $DestinationPortRange -eq "*") {
$message = "Warning! RG: $RG; NSG: $NSG_Name has SOURCE ANY Rule: $Rule to Destionation Port: $DestinationPortRange"
$message
}}}}}}