Reputation: 448
I am logging into Azure using azure cli as follows:
$login = az login
The output is as follows:
[
{
"cloudName": "AzureCloud",
"id": "xxxxxxxxxxxxxxxxxxx",
"isDefault": false,
"name": "ABC",
"state": "Enabled",
"tenantId": "yyyyyyyyyyyyy",
"user": {
"name": "xxxxxxx",
"type": "user"
}
},
{
"cloudName": "AzureCloud",
"id": "xxxxxxxxxxxxxxxxxxxx",
"isDefault": true,
"name": "PQR",
"state": "Enabled",
"tenantId": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"user": {
"name": "xxxxxxxxxx",
"type": "user"
}
}
]
I want to fetch the id value whose name is PQR. I was expecting i could do this as follows:
$login[1].id
But turns out $login is not a json object. I tried doing $login | ConvertTo-Json. Not working as i want.
Upvotes: 2
Views: 2493
Reputation: 26335
az login
in this case will just give you an array of lines of the output. You can check this with $login.GetType()
, which will give you System.Object[]
. You can use ConvertFrom-Json
to convert the array to a PowerShell custom object. Then you can simply access the second object's subscription id
property.
$login = az login
$json = $login | ConvertFrom-Json
Write-Output $json[1].id
# ID should be printed here
You can view the PSCustomObject properties with Get-Member
:
PS C:\> $json | Get-Member
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
cloudName NoteProperty string cloudName=AzureCloud
id NoteProperty string id=xxxx-xxxx-xxxx-xxxx
isDefault NoteProperty bool isDefault=True
name NoteProperty string name=xxxxxxx
state NoteProperty string state=Enabled
tenantId NoteProperty string tenantId=xxxx-xxxx-xxxx-xxxx
user NoteProperty System.Management.Automation.PSCustomObject user=@{[email protected]; type=user}
You can also have a look at Connect-AzAccount
, which is the Azure PowerShell way of logging in. A full tutorial can be found at Sign in with Azure PowerShell. az login
is the Azure CLI method of logging in, which is cross platform compatible.
Upvotes: 2