Misc/Set-ProperContext.ps1
function Set-ProperContext { [CmdletBinding(SupportsShouldProcess, ConfirmImpact="low")] Param( [Parameter(Mandatory=$false)] $settings = $null ) if ($null -eq $settings) { $settings = Import-Config } if ($PSCmdlet.ShouldProcess("Context", "This will set a new ")) { $context = Get-AzContext if ($context.Subscription.Name -ne $settings.subscription -or ($context.Tenant.Id -ne $settings.tenant -and $settings.tenant -ne "")) { try { try { if ($settings.tenant -ne "") { $context = Set-AzContext -Subscription $settings.subscription -Tenant $settings.tenant } else { $context = Set-AzContext -Subscription $settings.subscription } } catch { $os = (Get-CimInstance Win32_OperatingSystem) $isServerHost = $os.ProductType -eq 3 if ($isServerHost) { $context = Connect-AzAccount -Identity -TenantId $settings.tenant } else { $context = Connect-AzAccount -TenantId $settings.tenant } $context = Get-AzContext } } catch { throw "Could not connect to proper Azure context" } } $context } } |