Private/Add-CustomImageToGallery.ps1
# Will be called in VM function Global:Add-CustomImageToGallery { [CmdletBinding()] <# .SYNOPSIS Downloads the Business Central DVD and extracts it .DESCRIPTION ... #> param( [Parameter(Mandatory = $true, Position = 1)] [string] $ResourceGroupName, [Parameter(Mandatory = $true, Position = 2)] [string] $ResourceLocation, [Parameter(Mandatory = $true, Position = 3)] [string] $GalleryName, [Parameter(Mandatory = $true, Position = 4)] [string] $GalleryDefinitionName, [Parameter(Mandatory = $true, Position = 4)] [string] $GalleryPublisher, [Parameter(Mandatory = $true, Position = 4)] [string] $GalleryOffer, [Parameter(Mandatory = $true, Position = 4)] [string] $GallerySku, [Parameter(Mandatory = $true, Position = 4)] [string] $SourceImageName ) process { $image = Get-AzImage -ResourceGroupName $ResourceGroupName -ImageName $SourceImageName -ErrorAction SilentlyContinue if (-not($image)){ throw "Image $SourceImageName does not exist." return } $gallery = Get-AzGallery -ResourceGroupName $ResourceGroupName -Name $GalleryName -ErrorAction SilentlyContinue if (-not($gallery)) { Write-CustomHost -Message "Creating Image Gallery $GalleryName..." $gallery = New-AzGallery -ResourceGroupName $ResourceGroupName -Location $ResourceLocation -Name $GalleryName } $galleryImageDefinition = Get-AzGalleryImageDefinition -ResourceGroupName $ResourceGroupName -GalleryName $gallery.Name -Name $GalleryDefinitionName -ErrorAction SilentlyContinue if (-not($galleryImageDefinition)) { Write-CustomHost -Message "Creating Image Gallery Definition $GalleryDefinitionName..." $galleryImageDefinition = New-AzGalleryImageDefinition ` -GalleryName $gallery.Name ` -ResourceGroupName $ResourceGroupName ` -Location $ResourceLocation ` -Name $GalleryDefinitionName ` -OsState Generalized ` -OsType Windows ` -Publisher $GalleryPublisher ` -Offer $GalleryOffer ` -Sku $GallerySku } $targetregion = @{Name=$ResourceLocation;ReplicaCount=1} Write-CustomHost -Message "Adding Image $Name to Gallery." New-AzGalleryImageVersion -ResourceGroupName $ResourceGroupName -Location $ResourceLocation -GalleryName $gallery.Name ` -GalleryImageDefinitionName $galleryImageDefinition.Name -SourceImageId $image.Id -Name "1.0.0" -ReplicaCount 1 -TargetRegion $targetregion -AsJob | Out-Null Write-CustomHost -Message "Image $Name is being added to Gallery (job is running). Wait until publishing is ready before using the image in a ScaleSet" } } |