[Azure]使用Powershell導出所有訂閱下的ARM虛擬機的信息

針對腳本中涉及到的知識點說明:

1. 腳本輸出結果調用office的excel模塊輸出到一個excel的sheet中

2. 腳本中包含了通過powershell控制excel的cell格式,例如對齊方式,邊框樣式等等,行列寬度高度自適應(autofit),以及鎖定(freeze)首行首列的方法

3. 由於ARM模式下虛擬機,IP,網卡這些資源都是獨立的,互相之間引用,如果拿到每一臺虛擬機信息後,再去根據其NIC的Id和PublicIP的ID獲取對應的對象,那麼整個程序執行效率會大打折扣。所以腳本里面採用在執行前用3次請求把虛擬機,網卡,IP的所有對象獲取到本地內存,然後再後面引用的時候使用where條件篩選出需要的來提高執行效率

4. 腳本中其他的代碼就不贅述了,根據資源屬性得到每一列的值就好了

腳本如下:

Function GetResourceNameFromResourceId($resourceId)
{
    if ($resourceId -ne $null)
    {
        return $resourceId.Substring($resourceId.LastIndexOf('/') + 1);
    }
    return "";
}

Function GetResourcePropertyFromResourceId($resourceId, $propertyName)
{
    if ($resourceId -ne $null)
    {
        $propertyName = $propertyName + "/";
        $rgName = $resourceId.Substring($resourceId.IndexOf($propertyName) + $propertyName.Length);
        return $rgName.Substring(0, $rgName.IndexOf("/"));
    }
    return "";
}

$excel = New-Object -ComObject Excel.Application;
$workbook = $excel.Workbooks.add();
$sheet = $workbook.worksheets.Item(1);
$excel.Visible = $true;
# freeze the first column
$sheet.Application.ActiveWindow.SplitColumn = 1;
$sheet.Application.ActiveWindow.SplitRow = 1;
$sheet.Application.ActiveWindow.FreezePanes = $true;
$currentRow = 2;

$lineStyle = "microsoft.office.interop.excel.xlLineStyle" -as [type];
$colorIndex = "microsoft.office.interop.excel.xlColorIndex" -as [type];
$borderWeight = "microsoft.office.interop.excel.xlBorderWeight" -as [type];
$chartType = "microsoft.office.interop.excel.xlChartType" -as [type];
$VAlign = "microsoft.office.interop.excel.xlVAlign" -as [type];
$HAlign = "microsoft.office.interop.excel.xlHAlign" -as [type];

$titles = "Name", "Status", "Location", "Size", "OS Type", "Resource Group",  "Subscription ID", "Availability Set", "Use Managed Disk", "Data Disk Count",`
          "VNET", "Subnet", "Private IP", "Private IP Allocation Method", "Public IP", "Public IP Allocation Method", "DNS Name";

# set excel styles
for($i = 1; $i -le 17; $i++)
{
    $sheet.cells.item(1,$i).font.bold = $true;
    $sheet.cells.item(1,$i).borders.ColorIndex = $colorIndex::xlColorIndexAutomatic;
    $sheet.cells.item(1,$i).borders.weight = $borderWeight::xlThin;     #xlThick/xlMedium
    $sheet.cells.item(1,$i) = $titles[$i-1];
}
  
# generate excel cells
$subscriptions = Get-AzureRmSubscription;
foreach ($subscription in $subscriptions)
{
    if ($subscription.State -eq "Enabled")
    {
        [void](Select-AzureRmSubscription -SubscriptionId $subscription.SubscriptionId);
        Write-Host ("Querying VM information under subscription {0}" -f $subscription.SubscriptionName);
        
        # query information
        $vms = Get-AzureRmVM -Status -WarningAction Ignore;
        $nics = $null;
        $pips = $null;
        if ($vms.Count -gt 0)
        {
            $nics = Get-AzureRmNetworkInterface;
            $pips = Get-AzureRmPublicIpAddress;
        }

        foreach ($vm in $vms)
        {
            $nicInfo = $vm.NetworkProfile.NetworkInterfaces | where {$_.Primary -eq $true};
            if ($nicInfo -eq $null)
            {
                $nicInfo = $vm.NetworkProfile.NetworkInterfaces[0];
            }
            $nic = $nics | where {$_.Id -eq $nicInfo.Id};
            $primaryIPCfg = $nic.IpConfigurations | where {$_.Primary -eq $true};
            $subnetId = $primaryIPCfg.Subnet.Id;
            $subnetName = GetResourceNameFromResourceId $subnetId;
            $vnetName = GetResourcePropertyFromResourceId $subnetId "virtualNetworks";
        
            $publicIPAddressStr = New-Object System.Text.StringBuilder;
            $publicIPAddressAllocationStr = New-Object System.Text.StringBuilder;
            $privateIPAddressStr = New-Object System.Text.StringBuilder;
            $privateIPAddressAllocationStr = New-Object System.Text.StringBuilder;
            $privateIPAddressDNSStr = New-Object System.Text.StringBuilder;
            foreach ($ipconfig in $nic.IpConfigurations)
            {
                $pipInfo = $ipconfig.PublicIpAddress;
                if ($pipInfo -ne $null)
                {
                    $pip = $pips | where {$_.Id -eq $pipInfo.Id};
                    [void]($publicIPAddressStr.AppendLine($pip.IpAddress));
                    [void]($publicIPAddressAllocationStr.AppendLine($pip.PublicIpAllocationMethod));
                    [void]($privateIPAddressDNSStr.AppendLine($pip.DnsSettings.Fqdn));
                } else {
                    [void]($publicIPAddressStr.AppendLine());
                    [void]($publicIPAddressAllocationStr.AppendLine());
                    [void]($privateIPAddressDNSStr.AppendLine());
                }
                [void]($privateIPAddressStr.AppendLine($ipconfig.PrivateIpAddress));
                [void]($privateIPAddressAllocationStr.AppendLine($ipconfig.PrivateIpAllocationMethod));
            }
        
            $sheet.cells.item($currentRow,1) = $vm.Name;
            $sheet.cells.item($currentRow,2) = $vm.PowerState;
            $sheet.cells.item($currentRow,3) = $vm.Location;
            $sheet.cells.item($currentRow,4) = $vm.HardwareProfile.VmSize;
            $sheet.cells.item($currentRow,5) = $vm.StorageProfile.OsDisk.OsType.ToString();
            $sheet.cells.item($currentRow,6) = $vm.ResourceGroupName;
            $sheet.cells.item($currentRow,7) = $subscription.SubscriptionId;
            $sheet.cells.item($currentRow,8) = (GetResourceNameFromResourceId $vm.AvailabilitySetReference.Id);
            $sheet.cells.item($currentRow,9) = ($vm.StorageProfile.OsDisk.ManagedDisk -ne $null);
            $sheet.cells.item($currentRow,10) = $vm.StorageProfile.DataDisks.Count;
            $sheet.cells.item($currentRow,11) = $vnetName
            $sheet.cells.item($currentRow,12) = $subnetName;
            $sheet.cells.item($currentRow,13) = $privateIPAddressStr.ToString().Trim();
            $sheet.cells.item($currentRow,14) = $privateIPAddressAllocationStr.ToString().Trim();
            $sheet.cells.item($currentRow,15) = $publicIPAddressStr.ToString().Trim();
            $sheet.cells.item($currentRow,16) = $publicIPAddressAllocationStr.ToString().Trim();
            $sheet.cells.item($currentRow,17) = $privateIPAddressDNSStr.ToString().Trim();
            $currentRow++;
        }
    }
}

# auto fit cell sizes
$range = $sheet.usedRange;
$range.VerticalAlignment = $VAlign::xlVAlignTop;
$range.HorizontalAlignment = $HAlign::xlHAlignLeft;
$range.EntireColumn.AutoFit() | out-null;
$range.EntireRow.AutoFit() | out-null;
腳本運行方法:保存成.ps1文件,然後再Azure Powershell裏面執行(別忘了用Add-AzureRmAccount -EnvironmentName AzureChinaCloud登陸一下)

腳本運行結果(excel):




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章