PowerShell在Azure中没有要导出的数据时不会创建CSV。

huangapple go评论81阅读模式
英文:

Powershell does not create CSV if there is no data to export in Azure

问题

以下是翻译好的部分:

  1. 我正在尝试从Azure导出虚拟机数据如果订阅中有虚拟机则下面的脚本可以完美运行但是如果没有数据虚拟机),它不会创建.csv 文件我需要即使没有数据PowerShell也应该创建一个空白的 CSV 文件以下是我编写的脚本如果订阅中已创建虚拟机它可以正常运行
  2. function create($path) {
  3. $exists = Test-Path -path $path
  4. Write-Host "尝试以下路径:$path,它" $(If ($exists) {"存在"} Else {"不存在!"})
  5. if (!($exists)) { New-Item $path -itemType Directory }
  6. }
  7. # 读取文件内容
  8. $subs_file = "C:\Scrpting\Subscriptions\Subscriptions.xlsx"
  9. $azSubs = Import-Excel $subs_file
  10. $azSubs
  11. $output_folder = "C:\audit-automation"
  12. # 为输出数据创建文件夹
  13. create("$output_folder")
  14. # 遍历订阅
  15. ForEach ( $sub in $azSubs ) {
  16. # 订阅
  17. $azsub = $sub.Subscription
  18. # 应用程序
  19. $app = $sub.Application
  20. $azsub
  21. $app
  22. # 创建保存应用程序数据的文件夹
  23. Set-AzContext -SubscriptionName $azsub
  24. # 获取虚拟机信息
  25. $vms = Get-AzVM
  26. $vmrg = Get-AzVM | Select-Object "ResourceGroupName"
  27. $nics = get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null }
  28. # 创建保存数据的文件夹
  29. create("$output_folder$app")
  30. ForEach ($nic in $nics) {
  31. $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  32. $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
  33. $info.NICName = $nic.Name
  34. $info.VMName = $vm.Name
  35. $info.SubscriptionID = $azsub
  36. $info.ResourceGroupName = $vm.ResourceGroupName
  37. $info.PrivateIPAddress = $nic.IpConfigurations.PrivateIpAddress
  38. $PublicIPAddress =
  39. (Az vm list-ip-addresses --name $vm.Name --resource-group $vm.ResourceGroupName | ConvertFrom-Json).virtualMachine.network.publicIpAddresses.ipaddress
  40. $info.PublicIPAddress = if ($null -eq $PublicIPAddress ) { "Not Assigned" } else { $PublicIPAddress }
  41. $info.OS = $vm.StorageProfile.osDisk.osType
  42. $info.Status = ((Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status).Statuses[1]).code
  43. $info | Export-Csv -Path $output_folder$app$app-vm_data$((Get-Date).ToString("yyyy-MM-dd")).csv -Append
  44. }
  45. }

注意:上面的代码已被翻译成中文,其中的代码部分没有进行翻译。

英文:

I am trying to export VM data from Azure and below script is working perfect if subscription has VMs however it does create a .csv if there is no data (VMs) and I need that even if there is no data powershell should create a blank csv. Below is my script which is working fine if subscription has VMs created in it.

  1. function create($path) {
  2. $exists = Test-Path -path $path
  3. Write-Host "tried the following path: $path, it" $(If ($exists) {"Exists"} Else {"Does not Exist!"})
  4. if (!($exists)) { New-Item $path -itemType Directory }
  5. }
  6. # reading file contents
  7. $subs_file = "C:\Scrpting\Subscriptions\Subscriptions.xlsx"
  8. $azSubs = Import-Excel $subs_file
  9. $azSubs
  10. $output_folder = "C:\audit-automation"
  11. # creating folder for outputing data
  12. create("$output_folder")
  13. # New-Item $output_folder -itemType Directory
  14. # iterating over subscriptions
  15. ForEach ( $sub in $azSubs ) {
  16. # sub
  17. $azsub = $sub.Subscription
  18. # app
  19. $app = $sub.Application
  20. $azsub
  21. $app
  22. # creating folder to save data for apps
  23. # New-Item $output_folder$app -itemType Directory
  24. # setting config for azure
  25. Set-AzContext -SubscriptionName $azsub
  26. # GET VM INFO
  27. $vms = Get-AzVM
  28. $vmrg = Get-AzVM | Select-Object "ResourceGroupName"
  29. $nics = get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null }
  30. # creating folder to save
  31. # New-Item $output_folder$app\vm_info -itemType Directory
  32. create("$output_folder$app")
  33. ForEach ($nic in $nics) {
  34. $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  35. $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
  36. $info.NICName = $nic.Name
  37. $info.VMName = $vm.Name
  38. $info.SubscriptionID = $azsub
  39. $info.ResourceGroupName = $vm.ResourceGroupName
  40. $info.PrivateIPAddress = $nic.IpConfigurations.PrivateIpAddress
  41. $PublicIPAddress =
  42. (Az vm list-ip-addresses --name $vm.Name --resource-group $vm.ResourceGroupName | ConvertFrom-Json).virtualMachine.network.publicIpAddresses.ipaddress
  43. $info.PublicIPAddress = if ($null -eq $PublicIPAddress ) { "Not Assigned" } else { $PublicIPAddress }
  44. $info.OS = $vm.StorageProfile.osDisk.osType
  45. $info.Status = ((Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status).Statuses[1]).code
  46. $info | Export-Csv -Path $output_folder$app$app-vm_data$((Get-Date).ToString("yyyy-MM-dd")).csv -Append
  47. }}

答案1

得分: 0

在循环之外添加,因为 $vms 可能为空

  1. if (!($vms)){
  2. $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  3. $info | Export-Csv -Path $output_folder$app$app-vm_data$((Get-Date).ToString("yyyy-MM-dd")).csv -Append
  4. }
英文:

add outside the loop, since $vms may be empty

  1. if (!($vms)){
  2. $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  3. $info | Export-Csv -Path $output_folder$app$app-vm_data$((Get-Date).ToString("yyyy-MM-dd")).csv -Append

}

答案2

得分: 0

你可以删除create函数,然后用这一行替换:$null = New-Item $output_folder -ItemType Directory -Force。在文件系统中,-Force参数会使命令返回现有文件夹的DirectoryInfo对象,或者创建一个新文件夹并返回该对象。(不要在注册表键上使用这个参数!)

接下来,如果你首先将要输出的内容捕获到CSV文件中,就很容易检查是否有输出,如果没有,就写入一个空的CSV文件(只有标题会在其中)。

类似这样:

  1. # 读取文件内容
  2. $subs_file = "C:\Scrpting\Subscriptions\Subscriptions.xlsx"
  3. $azSubs = Import-Excel $subs_file
  4. $output_folder = "C:\audit-automation"
  5. # 创建用于输出数据的文件夹
  6. $null = New-Item $output_folder -ItemType Directory -Force
  7. # 遍历订阅
  8. foreach($sub in $azSubs) {
  9. # 订阅
  10. $azsub = $sub.Subscription
  11. # 应用程序
  12. $app = $sub.Application
  13. # 设置 Azure 配置
  14. Set-AzContext -SubscriptionName $azsub
  15. # 获取 VM 信息
  16. $vms = Get-AzVM
  17. $vmrg = Get-AzVM | Select-Object "ResourceGroupName"
  18. $nics = Get-AzNetworkInterface | Where-Object { $null -ne $_.VirtualMachine }
  19. # 创建用于保存数据的文件夹
  20. $null = New-Item (Join-Path -Path $output_folder -ChildPath $app) -ItemType Directory -Force
  21. # 捕获 foreach 循环的输出
  22. $result = foreach ($nic in $nics) {
  23. $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  24. $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
  25. $info.NICName = $nic.Name
  26. $info.VMName = $vm.Name
  27. $info.SubscriptionID = $azsub
  28. $info.ResourceGroupName = $vm.ResourceGroupName
  29. $info.PrivateIPAddress = $nic.IpConfigurations.PrivateIpAddress
  30. $PublicIPAddress = (Az vm list-ip-addresses --name $vm.Name --resource-group $vm.ResourceGroupName |
  31. ConvertFrom-Json).virtualMachine.network.publicIpAddresses.ipaddress
  32. $info.PublicIPAddress = if ($null -eq $PublicIPAddress ) { "Not Assigned" } else { $PublicIPAddress }
  33. $info.OS = $vm.StorageProfile.osDisk.osType
  34. $info.Status = ((Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status).Statuses[1]).code
  35. # 输出要在变量 $result 中收集的对象
  36. $info
  37. }
  38. # 检查一下现在是否有数据在变量 $result 中
  39. if (!@($result.Count)) {
  40. # 没有数据;创建一个只包含标题的空的 CSV 文件
  41. $result = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  42. }
  43. $outFile = Join-Path -Path $output_folder -ChildPath ('{0}\{0}-vm_data{1:yyyy-MM-dd}.csv' -f $app, (Get-Date))
  44. $result | Export-Csv -Path $outFile -NoTypeInformation
  45. }
英文:

You can remove the function create and replace that with just the one line $null = New-Item $output_folder -ItemType Directory -Force.
On file system, the -Force makes the cmdlet return either the DirectoryInfo object of an existing folder or create a new folder and return that.
(don't use this on registry keys!)

Next, if you capture the output you want in the CSV file first, it is easy enough to check if there is output or not and if not, write an empty csv file (only the headers will be in there)

Something like this:

  1. # reading file contents
  2. $subs_file = "C:\Scrpting\Subscriptions\Subscriptions.xlsx"
  3. $azSubs = Import-Excel $subs_file
  4. #$azSubs
  5. $output_folder = "C:\audit-automation"
  6. # creating folder for outputing data
  7. $null = New-Item $output_folder -ItemType Directory -Force
  8. # iterating over subscriptions
  9. foreach($sub in $azSubs) {
  10. # sub
  11. $azsub = $sub.Subscription
  12. # app
  13. $app = $sub.Application
  14. $azsub
  15. $app
  16. # setting config for azure
  17. Set-AzContext -SubscriptionName $azsub
  18. # GET VM INFO
  19. $vms = Get-AzVM
  20. $vmrg = Get-AzVM | Select-Object "ResourceGroupName"
  21. $nics = Get-AzNetworkInterface | Where-Object { $null -ne $_.VirtualMachine }
  22. # creating folder to save
  23. $null = New-Item (Join-Path -Path $output_folder -ChildPath $app) -ItemType Directory -Force
  24. # capture the output of the foreach loop
  25. $result = foreach ($nic in $nics) {
  26. $info = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  27. $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
  28. $info.NICName = $nic.Name
  29. $info.VMName = $vm.Name
  30. $info.SubscriptionID = $azsub
  31. $info.ResourceGroupName = $vm.ResourceGroupName
  32. $info.PrivateIPAddress = $nic.IpConfigurations.PrivateIpAddress
  33. $PublicIPAddress = (Az vm list-ip-addresses --name $vm.Name --resource-group $vm.ResourceGroupName |
  34. ConvertFrom-Json).virtualMachine.network.publicIpAddresses.ipaddress
  35. $info.PublicIPAddress = if ($null -eq $PublicIPAddress ) { "Not Assigned" } else { $PublicIPAddress }
  36. $info.OS = $vm.StorageProfile.osDisk.osType
  37. $info.Status = ((Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status).Statuses[1]).code
  38. # output the object to be collected in variable $result
  39. $info
  40. }
  41. # test if you actually have data now in the $result variable
  42. if (!@($result.Count)) {
  43. # no data; create an empty csv with just the headers
  44. $result = "" | Select VMName, ResourceGroupName, OS, PrivateIPAddress, PublicIPAddress, SubscriptionID, Status, NICName
  45. }
  46. $outFile = Join-Path -Path $output_folder -ChildPath ('{0}\{0}-vm_data{1:yyyy-MM-dd}.csv' -f $app, (Get-Date))
  47. $result | Export-Csv -Path $outFile -NoTypeInformation
  48. }

huangapple
  • 本文由 发表于 2023年2月14日 18:56:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定