Azure无VM数据时PowerShell未生成CSV,需实现空CSV生成
解决方案
修改后的脚本会确保即使订阅下无VM数据,也能生成包含表头的空白CSV文件:
function create($path) { $exists = Test-Path -path $path Write-Host "tried the following path: $path, it" $(If ($exists) {"Exists"} Else {"Does not Exist!"}) if (!($exists)) { New-Item $path -itemType Directory } } # 读取订阅文件 $subs_file = "C:\Scrpting\Subscriptions\Subscriptions.xlsx" $azSubs = Import-Excel $subs_file $output_folder = "C:\audit-automation" # 创建输出根目录 create("$output_folder") # 遍历每个订阅 ForEach ( $sub in $azSubs ) { $azsub = $sub.Subscription $app = $sub.Application # 设置当前Azure上下文 Set-AzContext -SubscriptionName $azsub | Out-Null # 获取VM和关联的NIC $vms = Get-AzVM $nics = Get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null } # 创建应用专属目录 create("$output_folder\$app") # 定义CSV输出路径 $csvPath = Join-Path -Path "$output_folder\$app" -ChildPath "$app-vm_data$((Get-Date).ToString("yyyy-MM-dd")).csv" # 初始化CSV文件(确保表头存在,无数据时生成空白文件) if (-not (Test-Path -Path $csvPath)) { $emptyTemplate = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName $emptyTemplate | Export-Csv -Path $csvPath -NoTypeInformation } # 遍历NIC并导出VM数据 ForEach ($nic in $nics) { $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName $vm = $vms | Where-Object { $_.Id -eq $nic.VirtualMachine.id } $info.NICName = $nic.Name $info.VMName = $vm.Name $info.SubscriptionID = $azsub $info.ResourceGroupName = $vm.ResourceGroupName $info.PrivateIPAddress = $nic.IpConfigurations.PrivateIpAddress $PublicIPAddress = (Az vm list-ip-addresses --name $vm.Name --resource-group $vm.ResourceGroupName | ConvertFrom-Json).virtualMachine.network.publicIpAddresses.ipaddress $info.PublicIPAddress = if ($null -eq $PublicIPAddress ) { "Not Assigned" } else { $PublicIPAddress } $info.OS = $vm.StorageProfile.osDisk.osType $info.Status = ((Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status).Statuses[1]).code $info | Export-Csv -Path $csvPath -Append -NoTypeInformation } }
关键修改说明
- 提前初始化CSV文件:在处理NIC之前,先检查CSV文件是否存在,不存在则用包含所有列的空对象生成带表头的文件,确保无数据时文件也会被创建
- 使用
Join-Path拼接路径:避免手动拼接路径时出现格式问题 - 添加
-NoTypeInformation参数:移除CSV文件顶部的类型信息行,让输出更规范 - 优化冗余代码:移除未使用的
$vmrg变量,添加| Out-Null抑制Set-AzContext的输出干扰
内容的提问来源于stack exchange,提问作者Saurabh
相关产品推荐
相关产品推荐

