Skip to content

Instantly share code, notes, and snippets.

@skmkzyk
Created May 21, 2021 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skmkzyk/8d01664817e4b515648507d7c14791a6 to your computer and use it in GitHub Desktop.
Save skmkzyk/8d01664817e4b515648507d7c14791a6 to your computer and use it in GitHub Desktop.
New-AzVMFromExistingResource function for creating VM from existing NIC and disks with availability set.
Function New-AzVMFromExistingResource() {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)] [string] $ResourceGroupName,
[Parameter(Mandatory = $true)] [string] $LocationName,
[Parameter(Mandatory = $true)] [string] $VMName,
[Parameter(Mandatory = $true)] [string] $VMSize,
[Parameter(Mandatory = $true)] [string] $AVSetName,
[Parameter(Mandatory = $true)] [string] $OSDiskName,
[Parameter(Mandatory = $true)] [string] $NICName
)
# 既存の OS Disk をつかむ
$OSDisk = Get-AzDisk -DiskName $OSDiskName -ResourceGroupName $ResourceGroupName
# 既存の NIC をつかむ
$NIC = Get-AzNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName
# 既存の AVSet をつかむ
$AVSet = Get-AzAvailabilitySet -ResourceGroupName $ResourceGroupName -Name $AVSetName
# 既存のリソースを組み合わせて VM を作成する
$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $VMSize -AvailabilitySetId $AVSet.Id
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -ManagedDiskId $OSDisk.Id -Windows -CreateOption Attach
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
$VirtualMachine = Set-AzVMBootDiagnostic -VM $VirtualMachine -Disable
New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -DisableBginfoExtension -Verbose
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment