Creates a new Azure VM using configuration discovered from an existing VM.
.DESCRIPTION
Recreates the source VM's size, Marketplace image reference, OS disk size/SKU,
subnet, NIC NSG (when attached at NIC level), accelerated networking, and
security type settings. Data disks are reported but not recreated in this version.
This does NOT copy the source VM's OS, files, installed software, data disk contents,
data disk contents, public IP, private IP, extensions, tags, or VM identity.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $SourceVM,
[Parameter(Mandatory)] [string] $SourceResourceGroup,
[Parameter(Mandatory)] [string] $NewVM,
[Parameter(Mandatory)] [string] $TargetResourceGroup,
[string] $TemplateFile = (Join-Path $PSScriptRoot 'clone-vm.bicep'),
[string] $TargetLocation,
[string] $TargetSubnetId,
[switch] $SkipDataDisks,
[switch] $SkipNicNsg,
[switch] $DisableBootDiagnostics
)
$ErrorActionPreference = 'Stop'
function Get-DiskSkuName {
param($Disk)
if ($Disk.Sku -and $Disk.Sku.Name) { return [string]$Disk.Sku.Name }
return 'Standard_LRS'
}
function Get-ResourceGroupAndNameFromId {
param([Parameter(Mandatory)][string]$ResourceId)
$parts = $ResourceId.TrimEnd('/') -split '/'
$rgIndex = [Array]::IndexOf($parts, 'resourceGroups')
if ($rgIndex -lt 0 -or ($rgIndex + 1) -ge $parts.Length) {
throw "Unable to parse resource group from resource ID: $ResourceId"
}
return @{ ResourceGroupName = $parts[$rgIndex + 1]; Name = $parts[-1] }
}
Write-Host "Checking Az modules and Azure login..." -ForegroundColor Cyan
if (-not (Get-Command Get-AzVM -ErrorAction SilentlyContinue)) {
throw "Az.Compute is not installed. Install with: Install-Module Az.Compute -Scope CurrentUser"
}
if (-not (Get-AzContext -ErrorAction SilentlyContinue)) {
Connect-AzAccount | Out-Null
}
Write-Host "Reading source VM configuration..." -ForegroundColor Cyan
$source = Get-AzVM -ResourceGroupName $SourceResourceGroup -Name $SourceVM
$sourceOsDiskId = $source.StorageProfile.OsDisk.ManagedDisk.Id
if (-not $source.StorageProfile.ImageReference -or -not $source.StorageProfile.ImageReference.Publisher) {
throw "The source VM does not expose a Marketplace image reference. This script creates a clean VM from an image; custom-image/specialized-disk VMs need a different approach."
}
$imageRef = @{
publisher = [string]$source.StorageProfile.ImageReference.Publisher
offer = [string]$source.StorageProfile.ImageReference.Offer
sku = [string]$source.StorageProfile.ImageReference.Sku
version = [string]$source.StorageProfile.ImageReference.Version
}
$sourceOsType = [string]$source.StorageProfile.OsDisk.OsType
if (-not $sourceOsType) { $sourceOsType = 'Windows' }
$osDiskParts = Get-ResourceGroupAndNameFromId -ResourceId $sourceOsDiskId
$osDisk = Get-AzDisk -ResourceGroupName $osDiskParts.ResourceGroupName -DiskName $osDiskParts.Name
$osDiskConfig = @{
diskSizeGB = [int]$osDisk.DiskSizeGB
sku = (Get-DiskSkuName $osDisk)
}
# NIC/subnet and NIC-level NSG discovery. Uses first primary NIC and first IP config.
$sourceNicId = $source.NetworkProfile.NetworkInterfaces[0].Id
$sourceNicParts = Get-ResourceGroupAndNameFromId -ResourceId $sourceNicId
$sourceNic = Get-AzNetworkInterface -ResourceGroupName $sourceNicParts.ResourceGroupName -Name $sourceNicParts.Name
$sourceIpConfig = $sourceNic.IpConfigurations | Select-Object -First 1
if (-not $TargetSubnetId) { $TargetSubnetId = $sourceIpConfig.Subnet.Id }
if (-not $TargetSubnetId) { throw 'Could not determine source subnet. Supply -TargetSubnetId.' }
$nicNsgId = ''
if (-not $SkipNicNsg -and $sourceNic.NetworkSecurityGroup) { $nicNsgId = $sourceNic.NetworkSecurityGroup.Id }
$accelerated = [bool]$sourceNic.EnableAcceleratedNetworking
# Recreate security profile when source VM is Trusted Launch or has a security type set.
$security = @{}
if ($source.SecurityProfile) {
if ($source.SecurityProfile.SecurityType) { $security.securityType = [string]$source.SecurityProfile.SecurityType }
if ($source.SecurityProfile.UefiSettings) {
$security.uefiSettings = @{}
if ($null -ne $source.SecurityProfile.UefiSettings.SecureBootEnabled) { $security.uefiSettings.secureBootEnabled = [bool]$source.SecurityProfile.UefiSettings.SecureBootEnabled }
if ($null -ne $source.SecurityProfile.UefiSettings.VtpmEnabled) { $security.uefiSettings.vTpmEnabled = [bool]$source.SecurityProfile.UefiSettings.VtpmEnabled }
}
}
# Data disks are intentionally not recreated by this template version.
if ($source.StorageProfile.DataDisks.Count -gt 0) {
Write-Warning "Source VM has $($source.StorageProfile.DataDisks.Count) data disk(s). This version does not create or attach data disks."
}
$deployLocation = if ($TargetLocation) { $TargetLocation } else { $source.Location }
$vmSize = [string]$source.HardwareProfile.VmSize
$adminUser = Read-Host "Enter local admin username for new VM"
$adminPass = Read-Host "Enter local admin password for new VM" -AsSecureString
#$cred = [pscredential]::new($adminUser, $adminPass)
#$adminPasswordPlain = $cred.GetNetworkCredential().Password
$adminPasswordPlain = [System.Net.NetworkCredential]::new("", $adminPass).Password
if (-not (Test-Path $TemplateFile)) { throw "Bicep template not found: $TemplateFile" }
if (-not (Get-Command New-AzResourceGroupDeployment -ErrorAction SilentlyContinue)) {
throw "Az.Resources is required. Install with: Install-Module Az.Resources -Scope CurrentUser"
}
if (-not (Get-Command bicep -ErrorAction SilentlyContinue)) {
throw "Standalone Bicep CLI is required to avoid the embedded Bicep compiler crash. Install it from https://aka.ms/bicep-install and retry."
}
# Compile Bicep to ARM JSON with the standalone CLI, then deploy the JSON. This
# avoids the embedded Bicep compilation path used by some Az.Resources versions.
$tempArmTemplate = Join-Path $env:TEMP ("clone-$NewVM-$([guid]::NewGuid().ToString('N')).json")
try {
Write-Host "Compiling Bicep template with standalone Bicep CLI..." -ForegroundColor Cyan
& bicep build $TemplateFile --outfile $tempArmTemplate
if ($LASTEXITCODE -ne 0 -or -not (Test-Path $tempArmTemplate)) {
throw "Bicep compilation failed. Run 'bicep build $TemplateFile' to view diagnostics."
}
Write-Host "Deploying new VM '$NewVM' to resource group '$TargetResourceGroup'..." -ForegroundColor Cyan
$deployment = New-AzResourceGroupDeployment `
-ResourceGroupName $TargetResourceGroup `
-Name "clone-$NewVM" `
-TemplateFile $tempArmTemplate `
-vmName $NewVM `
-location $deployLocation `
-vmSize $vmSize `
-subnetId $TargetSubnetId `
-imageReference $imageRef `
-osType $sourceOsType `
-osDiskConfig $osDiskConfig `
-networkSecurityGroupId $nicNsgId `
-enableAcceleratedNetworking $accelerated `
-securityProfile $security `
-adminUsername $adminUser `
-adminPassword (ConvertTo-SecureString -String $adminPasswordPlain -AsPlainText -Force) `
} finally {
if (Test-Path $tempArmTemplate) { Remove-Item $tempArmTemplate -Force -ErrorAction SilentlyContinue }
}
$adminPasswordPlain = $null
Write-Host "Deployment complete." -ForegroundColor Green
Write-Host "VM: $NewVM"
Write-Host "Location: $deployLocation"
Write-Host "VM size: $vmSize"
Write-Host "OS: $sourceOsType"
Write-Host "Image: $($imageRef.publisher)/$($imageRef.offer)/$($imageRef.sku):$($imageRef.version)"
if ($deployment.Outputs.vmId.Value) { Write-Host "VM ID: $($deployment.Outputs.vmId.Value)" }
Write-Warning "Data disks (if any) were created EMPTY. OS installation/software, data, extensions, public IP, original private IP, tags, and identity were not copied. Verify subnet/NSG/security settings before starting workloads."