使用 powershell,我需要获取租户内所有订阅的 Windows 虚拟机列表。我只需要带有标签 ApplicationName 且其值中包含 PROD 的虚拟机。
这是我当前的脚本:
# Get resource groups with the specified tag
$resourceGroups = Get-AzResourceGroup | Where-Object { $_.Tags -ne $null -and $_.Tags['ApplicationName'] -like "*PROD*" }
# Create an array to store the results
$results = @()
# Iterate through each resource group
foreach ($group in $resourceGroups) {
$groupName = $group.ResourceGroupName
$vms = Get-AzVM
foreach ($vm in $vms) {
if ($vm.StorageProfile.OSDisk.OSType -eq "Windows") {
$result = [ordered]@{
'VM Name' = $vm.Name
'Subscription' = $group.Subscription
'Resource Group' = $groupName
'Location' = $vm.Location
'Publisher' = $vm.StorageProfile.ImageReference.Publisher
'Plan' = $vm.StorageProfile.ImageReference.Sku
'Offer' = $vm.StorageProfile.ImageReference.Offer
}
$results += New-Object -TypeName PSObject -Property $result
}
}
}
# Output the results in a table format
$results | Format-Table -AutoSize
# Export the results to a CSV file
$results | Export-Csv -Path "C:\Users\XXXXXXXXXX\WindowsVMsList.csv" -NoTypeInformation
Write-Output "Script execution completed."
脚本输出中有 2 个问题,订阅列为空,并且未考虑 ApplicationName 标签过滤器。
请问有什么帮助吗?
我需要获取租户内所有订阅的 Windows 虚拟机列表。我只需要带有标签 ApplicationName 且其值中包含 PROD 的虚拟机。
这是更新后的
PowerShell
脚本,用于获取 tenant中标有 指定标签的所有
VMs
。
$vmList = @()
$sub = Get-AzSubscription
foreach ($subnames in $sub) {
$subid = $subnames.Id
Set-AzContext -SubscriptionId $subId
$vms = Get-AzVM | Where-Object { $_.StorageProfile.OsDisk.OsType -eq "Windows" -and $_.Tags["ApplicationName"] -like "*PROD*" }
foreach ($vm in $vms) {
$subId = $vm.Id.Split('/')[2]
$vmList += [PSCustomObject]@{
Name = $vm.Name
SubscriptionID = $subId
ResourceGroup = $vm.ResourceGroupName
Location = $vm.Location
OsProfile = $vm.OsProfile
VMTags = $vm.Tags
}
}
}
$vmList
$vmList | Export-Csv -Path "C:\Users\XXXXX\WindowsVMsList.csv" -NoTypeInformation
输出