如题,使用Powershell将一个账号中所有订阅下ASM模式的存储账号过一遍,将其中的vhd文件对应的虚拟机找出来汇总成表。
脚本如下:
$Cred = New-Object System.Management.Automation.PSCredential("XXXXXXXXX@XXXXXXXXX.partner.onmschina.cn",(ConvertTo-SecureString "XXXXXXXXX" -AsPlainText -Force));
$AzureRMCred = Get-Credential -Credential $Cred;
Add-AzureAccount -Environment AzureChinaCloud -Credential $AzureRMCred;
$disk_url_mapping = @{};
$vm_url_mapping = @{};
$storage_url_mapping = @{};
Function FillStorageMapping()
{
$storage_url_mapping.Clear();
$storages = Get-AzureStorageAccount;
foreach($storage in $storages)
{
$storageAccountName = $storage.StorageAccountName;
$blobs = Get-AzureStorageBlob -Context $storage.Context -Container vhds -ErrorAction Ignore;
foreach ($blob in $blobs)
{
if ($blob.BlobType -eq "PageBlob")
{
$url = $blob.ICloudBlob.Uri.AbsoluteUri;
if ($url.EndsWith(".vhd") -and !$storage_url_mapping.ContainsKey($url))
{
$storage_url_mapping.Add($url, $storageAccountName);
}
}
}
}
}
Function FillDiskMapping()
{
$disk_url_mapping.Clear();
$disks = Get-AzureDisk;
foreach($disk in $disks)
{
$disk_url_mapping.Add($disk.MediaLink.AbsoluteUri, $disk.DiskName);
}
}
Function FillVmMapping()
{
$vm_url_mapping.Clear();
$vms = Get-AzureVM;
foreach($vm in $vms)
{
$cloudServiceAndVM = $vm.ServiceName + "#" + $vm.Name;
$osDiskUrl = $vm.VM.OSVirtualHardDisk.MediaLink.AbsoluteUri;
$vm_url_mapping.Add($osDiskUrl, $cloudServiceAndVM);
$dataDisks = $vm.VM.DataVirtualHardDisks;
foreach($dataDisk in $dataDisks)
{
$dataDiskUrl = $dataDisk.MediaLink.AbsoluteUri;
$vm_url_mapping.Add($dataDiskUrl, $cloudServiceAndVM);
}
}
}
Function ShowStorageVhdOwners()
{
$subscriptions = Get-AzureSubscription;
$results = New-Object System.Collections.ArrayList;
foreach($subscription in $subscriptions)
{
$subscriptionName = $subscription.SubscriptionName;
Select-AzureSubscription -SubscriptionName $subscriptionName;
FillStorageMapping;
FillDiskMapping;
FillVmMapping;
foreach ($url in $storage_url_mapping.Keys)
{
$storageAccount = $storage_url_mapping[$url];
$disk = $disk_url_mapping[$url];
$cloudService = "";
$vmName = "";
if ($vm_url_mapping.ContainsKey($url))
{
$cloudServiceAndVM = $vm_url_mapping[$url].Split('#');
$cloudService = $cloudServiceAndVM[0];
$vmName = $cloudServiceAndVM[1];
}
$results.Add(@{SubscriptionName=$subscriptionName; StorageAccountName=$storageAccount; VhdUrl=$url; DiskName=$disk; CloudService=$cloudService; VirtualMachineName=$vmName;});
}
}
$results | Select @{Name="SubscriptionName"; Expression={$_["SubscriptionName"]}}, @{Name="StorageAccountName";Expression={$_["StorageAccountName"]}}, @{Name="VHD Url"; Expression={$_["VhdUrl"]}}, @{Name="DiskName"; Expression={$_["DiskName"]}}, @{Name="CloudService"; Expression={$_["CloudService"]}}, @{Name="VirtualMachineName"; Expression={$_["VirtualMachineName"]}} | Out-GridView;
}
ShowStorageVhdOwners
脚本输出: