如何解决Azure PowerShell - 虚拟机标记报告
我有兴趣查询 Azure 订阅以提供标记报告,该报告指示每个 VM 的 VM 名称、Azure 区域以及标记和标记值。
我当前的脚本为我提供了所有数据,每个标签的标签值除外。我的输出显示的结果好像标签不存在一样。
有人对我的剧本有什么建议吗?谢谢!
参数( [参数(强制= $true)] [字符串] $subscriptionName )
Select-AzSubscription -Subscription $subscriptionName
$allTags = Get-AzTag
$allVMs = Get-AzVM
$vminformation = @() foreach ($vm in $allVMs) {
$vminformationObject = New-Object PSObject
$vmName = $vm.Name
$vmRegion = $vm.Location
$vminformationObject | Add-Member -MemberType NoteProperty -Name "VM_Name" -Value $vmName
$vminformationObject | Add-Member -MemberType NoteProperty -Name "VM_Region" -Value $vmRegion
$vm_tags = $vm.tags
foreach ($tag in $allTags) {
$IfTagExists = $false
foreach ($vmtag in $vm_tags) {
if ($tag.name -like $vmtag.keys) {
$IfTagExists = $true
$vminformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value $vmtag.$($tag.Name)
break
}
}
if ($IfTagExists -eq $false) {
$vminformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value "--"
}
}
$vminformation += $vminformationObject }
$vm信息|导出-Csv "path.csv" -NoTypeinformation -Force
解决方法
这里的问题是比较语句 $tag.name -like $vmtag.keys
。由于左侧值是标量而右侧值是集合或列表,因此您需要使用包含 comparison operator。最简单的选项是 -in
或 -contains
。
# Option 1
# Use -in when singular item is on the LHS and collection is on RHS
if ($tag.name -in $vmtag.keys) {
$IfTagExists = $true
$vmInformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value $vmtag.$($tag.Name)
break
}
# Option 2
# Use -contains when singular item is on the RHS and collection is on LHS
if ($vmtag.keys -contains $tag.name) {
$IfTagExists = $true
$vmInformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value $vmtag.$($tag.Name)
break
}
,
我参加聚会有点晚了,我想提一下,如果您尝试将结果导出到 CSV 文件,则会遇到问题。根据 Microsoft Export-CSV 根据您提交的第一个对象的属性组织文件。如果剩余的对象没有指定的属性之一,则该对象的属性值为空,由两个连续的逗号表示。如果其余对象具有其他属性,则这些属性值不会包含在文件中。
您的脚本也会运行得更慢,因为您使用了变量 $allTags = Get-AzTag 而不是仅过滤所有 VM 中的通用标记,正如您在变量 $ 中看到的那样AllVMsTagKeys 在下面的脚本中,它将以更快、更清晰的方式执行您想要的所有操作,并将结果导出到桌面上的 CSV 文件:
$VMs = Get-AzVM -Status
$AllVMsTagKeys = $VMs.Tags.Keys | Sort-Object -Unique
foreach ( $VM in $VMs ) {
$Output = [PSCustomObject]@{
VMName = $VM.Name
VMRegion = $VM.Location
ResourceGroup = $VM.ResourceGroupName
PowerState = $VM.PowerState
}
foreach ( $VMTagKey in $AllVMsTagKeys ) {
Add-Member -InputObject $Output -Force -NotePropertyName $VMTagKey -NotePropertyValue $VM.Tags[$VMTagKey]
}
$Output
$Output | Export-Csv -NoTypeInformation -Append -Path $env:USERPROFILE\Desktop\VMsWithTags.csv
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。