[Azure]使用Powershell导出所有订阅下的ARM虚拟机的信息

news/2024/7/21 0:44:52 标签: Azure, Powershell, ARM, VM, Excel

针对脚本中涉及到的知识点说明:

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):





http://www.niftyadmin.cn/n/877872.html

相关文章

python里自带的绘画库是_【自学Python】DAY 4 绘画大师——turtle库(超详细)

自学Python DAY 4 目录turtle库介绍 turtle库使用 turtle的实例(源代码分享) 库我之前发的百科已经详细的介绍了,不知道的点击下方链接查看!博文-宇辰:【Python百科】库​zhuanlan.zhihu.com 库 (library&a…

c# string 转 datetime_Python:Numpy库基础分析——详解datetime类型的处理

Python:Numpy库基础分析——详解datetime类型的处理关于时间的处理,Python中自带的处理时间的模块就有time 、datetime、calendar,另外还有扩展的第三方库,如dateutil等等。通过这些途径可以随心所欲地用Python去处理时间。当我们…

Automatic Maintenance导致CPU跑满

今天使用电脑的时候突然发现超级卡,看了一下,CPU持续100%:感觉莫名其妙,机器上面什么也没跑,看资源管理器里面有一个名字叫TiWorker的进程在搞事情:看描述并不是病毒,又看到右下角提示"Mai…

[Azure]通过waagent代码找到临时磁盘的设备名

Azure的Linux虚拟机默认会有一个临时磁盘,正常情况下设备名是/dev/sdb,但是由于设备识别顺序是随机的,所以重启的时候,临时磁盘的设备名可能未必是/dev/sdb,那么waagent是如何将/dev/sdb挂在到/mnt/resource下的呢&…

[Azure]Azure Storage Access Policy使用小实验

Azure Storage的Container除了可以设置Public Access Level之外:还可以定义一些Stored Access Policy:Stored Access Policy是属于单个容器的,不同容器之间的Stored Access Policy是互相独立的。 Stored Access Policy可以用于生成SAS Token(…

antd option宽度自适应_齿轮干货:自适应网站和响应式网站有哪些差异

随着大屏智能手机以及ipad等通讯设备的广泛应用,网站样式风格也与时俱进,在满足PC端计算机的浏览时,移动端同样适合访客浏览,作为一些企业公司和个人,他们在网络营销方面有着更加严格的需求,既要符合网站品…

[Excel]Excel函数和用法(1)——绝对引用$的用法

如果我们希望公式拖拽的时候,横向拖拽的时候列号不自动增加,在列名前加$,如果我们希望行号不自动增加,在行号前面加$,比如: 我们再行号“1”前面加了$,然后拖拽之后,行号不变&#…