如何使用 PowerShell 导出 Azure 虚拟机标签?

powershellmicrosoft technologiessoftware & coding

使用 PowerShell 获取已应用的 Azure 虚拟机标签有两种方法。

  • 使用 Azure 虚拟机的 Tags 属性
  • 使用 Get-AZTag 命令。

示例

PS C:\> Get-AzVM -VMName Testmachine2k12 | Select -ExpandProperty Tags
Key          Value
---          -----
Patching_Day Sunday
Owner       Chirag

另一种方法是使用 Get-AZTag 命令。

PS C:\> $vm = Get-AzVM -VMName TestMachine2k12
PS C:\> Get-AzTag -ResourceId $vm.Id | Select -ExpandProperty Properties

输出

TagsProperty
------------
{[Owner, Chirag], [Patching_Day, Sunday]}

我们需要导出此标签,而存储标签的最佳方式是使用 JSON 文件。

Get-AzVM -VMName Testmachine2k12 | Select -ExpandProperty Tags | ConvertTo-Json | Out-File C:\Temp\VMTag.json

您可以看到标签文件存储在 C:\temp 文件夹中,文件名为 VMTag.json。

如果您想将标签存储为 CSV 文件格式,可以使用以下命令。

Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags | ConvertTo-Json | ConvertFrom-Json | Export-Csv C:\Temp\TestMachine2k16tags.csv -NoTypeInformation

上述命令将 Azure VM TestMachine2k16 标签存储为 C:\Temp\TestMachine2k16tags.CSV 格式。


相关文章