Private/New-VMMetricsStorageContext.ps1
|
function New-VMMetricsStorageContext { <# .SYNOPSIS Resolves account-key auth and returns a ready storage context, ensuring the target container exists. .DESCRIPTION Account-key authentication (per design). The key is taken from -StorageAccountKey when supplied, otherwise fetched from the control plane via Get-AzStorageAccountKey using -ResourceGroupName (works in Cloud Shell where the signed-in identity has control-plane rights). The container is created if missing, with no public access. .PARAMETER StorageAccountName Target storage account. .PARAMETER ContainerName Blob container; created if absent. .PARAMETER StorageAccountKey Account key. If omitted, -ResourceGroupName must be given to fetch it. .PARAMETER ResourceGroupName Resource group of the storage account, used to fetch the key when not supplied. .OUTPUTS Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory)] [string] $StorageAccountName, [Parameter(Mandatory)] [string] $ContainerName, [string] $StorageAccountKey, [string] $ResourceGroupName ) if (-not $StorageAccountKey) { if (-not $ResourceGroupName) { throw "Provide -StorageAccountKey, or -StorageAccountResourceGroup so the key can be fetched." } Write-Verbose "Fetching account key for $StorageAccountName from RG $ResourceGroupName." $keys = Get-AzStorageAccountKey -ResourceGroupName $ResourceGroupName -Name $StorageAccountName -ErrorAction Stop $StorageAccountKey = $keys[0].Value } $ctx = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey -ErrorAction Stop $container = Get-AzStorageContainer -Name $ContainerName -Context $ctx -ErrorAction SilentlyContinue if (-not $container -and $PSCmdlet.ShouldProcess($ContainerName, "Create blob container")) { Write-Verbose "Creating container '$ContainerName'." New-AzStorageContainer -Name $ContainerName -Context $ctx -Permission Off -ErrorAction Stop | Out-Null } return $ctx } |