You can use the same PowerShell script to take snapshots of both Windows and Linux VMs, but you will need to make some modifications to explicitly specify the OS type and ensure the snapshot type is set to Full.
Modifications Needed:
- Specify OS Type: You can determine the OS type of the VM and set the
-OsTypeparameter accordingly when creating the snapshot configuration. You can do this by checking the OS type of the VM before taking the snapshot. - Ensure Full Snapshot: The
-CreateOptionparameter in theNew-AzSnapshotConfigcmdlet should be set toCopy, which you are already doing. This will create a full snapshot of the disk.
Example Script Modification:
Here’s how you might modify your script to handle both types of VMs:
# Define VM details
$VmNames = @(
@{ Name = "WinAppVM01"; ResourceGroup = "Windows-ResourceGroup"; OsType = "Windows" },
@{ Name = "LinuxAppVM01"; ResourceGroup = "Linux-ResourceGroup"; OsType = "Linux" }
)
foreach ($vmDetails in $VmNames) {
$vm = Get-AzVM -Name $vmDetails.Name -ResourceGroupName $vmDetails.ResourceGroup
$loc = $vm.Location
Write-Output "VM $($vm.name) OS Disk Snapshot Begin"
$snapshotdisk = $vm.StorageProfile
$OSDiskSnapshotConfig = New-AzSnapshotConfig -SourceUri $snapshotdisk.OsDisk.ManagedDisk.id -CreateOption Copy -Location $loc -OsType $vmDetails.OsType
$snapshotNameOS = "$($snapshotdisk.OsDisk.Name)_snapshot_$(Get-Date -Format MMddyyyy)"
# OS Disk Snapshot
try {
New-AzSnapshot -ResourceGroupName $vmDetails.ResourceGroup -SnapshotName $snapshotNameOS -Snapshot $OSDiskSnapshotConfig -ErrorAction Stop
} catch {
$_
}
Write-Output "VM $($vm.name) OS Disk Snapshot End"
# Data Disk Snapshots
Write-Output "VM $($vm.name) Data Disk Snapshots Begin"
$dataDisks = ($snapshotdisk.DataDisks).name
foreach ($datadisk in $dataDisks) {
$dataDisk = Get-AzDisk -ResourceGroupName $vm.ResourceGroupName -DiskName $datadisk
Write-Output "VM $($vm.name) data Disk $($datadisk.Name) Snapshot Begin"
$DataDiskSnapshotConfig = New-AzSnapshotConfig -SourceUri $dataDisk.Id -CreateOption Copy -Location $loc
$snapshotNameData = "$($datadisk.name)_snapshot_$(Get-Date -Format MMddyyyy)"
New-AzSnapshot -ResourceGroupName $vmDetails.ResourceGroup -SnapshotName $snapshotNameData -Snapshot $DataDiskSnapshotConfig -ErrorAction Stop
Write-Output "VM $($vm.name) data Disk $($datadisk.Name) Snapshot End"
}
Write-Output "VM $($vm.name) Data Disk Snapshots End"
}
In this modified script, you loop through an array of VM details, allowing you to handle both Windows and Linux VMs accordingly. The -OsType parameter is set based on the VM's OS type, ensuring the correct configuration for each VM.
References: