我得到了下面的代码,它工作得很好,但是我检查是否找到 vnet 配对的方式有点错误。
这就是代码的样子。
$existing_peering = az network vnet peering show -g 'xx' -n 'ccc' --vnet-name 'ccc'
if ($existing_peering) {
write-output 'Peering exists'
}
$existing_peering
的输出如下。
{
"allowForwardedTraffic": true,
"allowGatewayTransit": true,
"allowVirtualNetworkAccess": true,
"doNotVerifyRemoteGateways": false,
"etag": "W/\"xxxxxx\"",
"id": "/subscriptions/fdfd",
"name": "xxxx",
"peeringState": "Disconnected",
"peeringSyncLevel": "FullyInSync",
"provisioningState": "Succeeded",
"remoteAddressSpace": {
"addressPrefixes": [
"10.77.0.0/16"
]
},
"remoteBgpCommunities": null,
"remoteVirtualNetwork": {
"id": "/subscriptions/",
"resourceGroup": "my-rg"
},
"remoteVirtualNetworkAddressSpace": {
"addressPrefixes": [
"10.77.0.0/16"
]
},
"remoteVirtualNetworkEncryption": null,
"resourceGroup": "cccc",
"resourceGuid": "ggggggggggg",
"type": "Microsoft.Network/virtualNetworks/virtualNetworkPeerings",
"useRemoteGateways": false
}
我想获取
name
的值以及 if 语句的求值方式,我不确定这是否是正确的方法,有时我发现如果 AZ cli 找不到对象,则 if $existing_peering
的值
可能是错误消息而不是预期返回的对象,并且当评估 IF
语句时,它可能会做错误的事情。
我创建了虚拟网络和对等 vnet,名称为
vnet1-vnet2
,如下所示:
要仅获取
name
的值,您可以使用以下命令:
$existing_peering = az network vnet peering show -g "<RGName>" -n "<PeeredvnetName>" --vnet-name "<VnetName>" --query "name" --output tsv
if ($existing_peering) {
Write-Output "Peering exists: $existing_peering"
} else {
Write-Output "Peering does not exist"
}
输出:
或者按照Abraham Zinala的建议,您可以使用
ConvertFrom-Json
通过修改脚本将其变成对象,如下所示:
$existing_peerings = az network vnet peering show -g "xxxx" -n "xxxx" --vnet-name "xxx" | ConvertFrom-Json
foreach ($peering_info in $existing_peerings) {
if ($peering_info.name) {
Write-Output 'Peering exists'
# You can access other properties like $peering_info.name here
}
}
输出: