title: Powershell Try and Catch in a loop
body: <p>I am trying to pull a report of all C:\ drive usage for windows 7 machine in our ESX farm. My initial ps codes will extract all windows 7 machine nto a csv file (sample picture below). I would like to ideally query the disk space with the DNS name first and if it fails due to RPC error, it should then catch the error and run the command again using the IP address instead. This is because there are instances that the dns entry does not get registered on our DNS and there are also times where the ESX sees 169.x.x.x IP during the query which would then gets polled by DNS name first.</p>
  
  <p>Issue here is that, I am not able to catch the RPC failure with the catch command. In the sample below, I have purposely filled up the .csv file with dummy dns names hoping that it will catch the error and execute the command in the catch portion. Unfortunately, it seems not to be working.</p>
  
  <p>Anyone here can shade some light on this one ?</p>
  
  <p><a href="https://i.stack.imgur.com/lZUQs.png" rel="nofollow noreferrer">CSV File Sample</a></p>
  
  <p><a href="https://i.stack.imgur.com/lZUQs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lZUQs.png" alt="csv file"></a></p>
  
  <pre><code>$Win7JumpboxList = import-csv 'D:\Win7DiskSpace\Win7PoweredOn.csv' |
  ForEach-Object {
      try {
          Get-WmiObject -Class win32_volume -ComputerName $_.DnsName -Filter "drivetype=3 and DRIVELETTER = 'C:' " | Select-Object @{LABEL='Computer';EXPRESSION={$_.pscomputername}}, DriveLetter, @{LABEL="Capacity (GB)";e={[math]::round($_.Capacity/1GB, 2)}}, @{LABEL="FreeSpace (GB)";e={[math]::round($_.FreeSpace/1GB, 2)}},@{LABEL="FreeSpace (%)";e={[int]($_.Freespace*100/$_.Capacity)}} -ErrorAction Stop
      }
      catch [System.Runtime.InteropServices.COMException] {
          Get-WmiObject -Class win32_volume -ComputerName $_.IPAddress -Filter "drivetype=3 and DRIVELETTER = 'C:' " | Select-Object @{LABEL='Computer';EXPRESSION={$_.pscomputername}}, DriveLetter, @{LABEL="Capacity (GB)";e={[math]::round($_.Capacity/1GB, 2)}}, @{LABEL="FreeSpace (GB)";e={[math]::round($_.FreeSpace/1GB, 2)}},@{LABEL="FreeSpace (%)";e={[int]($_.Freespace*100/$_.Capacity)}}
      }
  }
  
  $Win7JumpboxList | Export-Csv D:\Win7DiskSpace\Win7DiskSpace.csv -NoTypeInformation -force
  </code></pre>