本脚本对ASM虚拟机进行快照的创建,原理是针对给定的虚拟机的系统盘和全部数据盘进行快照。在调用脚本之前,需要用Add-AzureAccount -Environment AzureChinaCloud登陆一下或者导入订阅。
脚本如下:
param(
#The name of the subscription to take all the operations within.
[Parameter(Mandatory = $true)]
[string]$SubscriptionName,
# The name of the storage account to enumerate.
[Parameter(Mandatory = $true)]
[string]$ServiceName,
# The name of the storage container to enumerate.
[Parameter(Mandatory = $true)]
[string]$VMName
)
Select-AzureSubscription -SubscriptionName $SubscriptionName;
#Get VM
$VM = Get-AzureVM -ServiceName $ServiceName -Name $VMName;
#Get Disks
$OSDisk = $VM.VM.OSVirtualHardDisk;
$DataDisks = $VM.VM.DataVirtualHardDisks;
Function CreateSnapshot($Disk)
{
$AbsoluteUri = $Disk.MediaLink.AbsoluteUri;
$StorageAccountName = $AbsoluteUri.Substring(8, $AbsoluteUri.IndexOf(".blob.core.chinacloudapi.cn") - 8);
$ContainerPathIndex = $AbsoluteUri.IndexOf("blob.core.chinacloudapi.cn/") + 27;
$ContainerName = $AbsoluteUri.SubString($ContainerPathIndex, $AbsoluteUri.IndexOf('/', $ContainerPathIndex) - $ContainerPathIndex);
$BlobName = $AbsoluteUri.SubString($AbsoluteUri.LastIndexOf('/') + 1);
$storageAccessKey = (Get-AzureStorageKey -StorageAccountName $StorageAccountName).Primary;
$storageContext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $storageAccessKey -Endpoint "core.chinacloudapi.cn";
$blobClient = $storageContext.Context.StorageAccount.CreateCloudBlobClient();
$blobContainer = $blobClient.GetContainerReference($ContainerName);
$blob = $blobContainer.GetBlockBlobReference($blobName);
$Blob.CreateSnapshot() | Out-Null;
}
Write-Host "Creating OS Disk Snapshot...";
CreateSnapshot $OSDisk;
Write-Host "Finished Create OS Disk Snapshot.";
Write-Host "Creating Data Disk Snapshot(s)...";
Foreach($DataDisk in $DataDisks)
{
Write-Host "Creating snapshot for " $DataDisk.DiskName;
CreateSnapshot $DataDisk;
Write-Host "Finished create snapshot for " $DataDisk.DiskName;
}
Write-Host "Finished Create Data Disk Snapshot(s).";
执行示例:
[ASM]CreateSnapshotsForSingleVM.ps1 -SubscriptionName <Subscription Name> -ServiceName <CloudService Name> -VMName <VM Name>
Creating OS Disk Snapshot...
Finished Create OS Disk Snapshot.
Creating Data Disk Snapshot(s)...
Creating snapshot for DanServerTest-DanCentOS65-0-201606160509070764
Finished create snapshot for DanServerTest-DanCentOS65-0-201606160509070764
Creating snapshot for DanServerTest-DanCentOS65-1-201606160510300054
Finished create snapshot for DanServerTest-DanCentOS65-1-201606160510300054
Creating snapshot for DanServerTest-DanCentOS65-2-201606160511220008
Finished create snapshot for DanServerTest-DanCentOS65-2-201606160511220008
Creating snapshot for DanServerTest-DanCentOS65-3-201606160525080673
Finished create snapshot for DanServerTest-DanCentOS65-3-201606160525080673
Finished Create Data Disk Snapshot(s).