Skip to content

Instantly share code, notes, and snippets.

@Satak
Created April 15, 2021 08:44
Show Gist options
  • Save Satak/03dfa2fab1e0a5b4c3728fd8e7481479 to your computer and use it in GitHub Desktop.
Save Satak/03dfa2fab1e0a5b4c3728fd8e7481479 to your computer and use it in GitHub Desktop.
Azure account cmdlets
function New-AzureAccount {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ClientId,
[Parameter(Mandatory)]
[string]$ClientSecret,
[Parameter(Mandatory)]
[string]$TenantId
)
az login --service-principal --username $ClientId --password $ClientSecret --tenant $TenantId
}
function Get-AzureAccount {
[CmdletBinding(DefaultParameterSetName = "All")]
param (
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ByName', Mandatory)]
[string]$Name,
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ById', Mandatory)]
[string]$Id
)
Begin {
$query = "[]"
if ($Name) {
$query = "[?name == '$Name']"
}
elseif ($Id) {
$query = "[?id == '$Id']"
}
}
Process {
az account list --query "$($query).{id: id, name: name, isDefault: isDefault, user: user.type}" | ConvertFrom-Json
}
End {}
}
function Set-AzureAccount {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, HelpMessage = 'Name or Id of the Azure Subscription')]
[string]$Id
)
Begin {}
Process {
az account set --subscription $Id
}
End {
Write-Output "Azure subscription '$Id' set as a default account."
}
}
function Remove-AzureAccount {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]$Id
)
Begin {
$azureProfileFilePath = "$HOME\.azure\azureProfile.json"
}
process {
$filteredList = Get-Content $azureProfileFilePath | ConvertFrom-Json -Depth 5 | Select-Object -ExpandProperty subscriptions | Where-Object { $_.id -ne $Id }
@{subscriptions = $filteredList } | ConvertTo-Json -Depth 5 | Set-Content $azureProfileFilePath
}
End {
Write-Output "Azure subscription '$Id' removed from 'azureProfile.json'."
}
}
function Get-AzureResourceGroup {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias("Name")]
[string]$SubscriptionName
)
Begin {
$query = "[].{name: name, location: location}"
}
process {
if ($SubscriptionName) {
az group list --query $query --subscription $SubscriptionName | ConvertFrom-Json | Sort-Object location, name | Select-Object Location, Name, @{ Name = 'subscription'; Expression = { $SubscriptionName } }
}
else {
az group list --query $query | ConvertFrom-Json | Sort-Object location, name
}
}
End {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment