3 Replies Latest reply on Mar 20, 2013 5:27 PM by mattboren

    how to append the csv file

    td_sk Enthusiast

      Hi all,

        Thanks in advance.

               In the following script how to append the csv file. I am trying to get datastore details of the list of vms in the csv file.

           Add-PSSnapin VMware.VimAutomation.Core
      Connect-VIServer 192.168.1.125

      ##VMname.csv having list of vms ####
      $vm = Import-csv c:\scripts\vmname.csv
           foreach ($line in $vm) {
               Get-datastore -vm $line.name | Select-Object $line.name,name,FreeSpaceGB | Export-Csv c:\scripts\ds.csv -NoTypeInformation
        }

      Not able to append the result to my csv file. Also I need to add the vms os type of each vm. Please help.

       

      Thanks

        • 1. Re: how to append the csv file
          GuilhermeStela Enthusiast

          Try this:

           

           

           

           

           

          Add-PSSnapin VMware.VimAutomation.Core
          Connect-VIServer 192.168.1.125
          
          $vm = Import-csv c:\scripts\vmname.csv
          
           function OutRel(){
          
            foreach ($line in $vm) {
                   Get-datastore -vm $line.name | Select-Object $line.name,name,FreeSpaceGB 
            }
          
          }
          
          OutRel | Export-Csv c:\scripts\ds.csv -NoTypeInformation
          
          • 2. Re: how to append the csv file
            GuilhermeStela Enthusiast

            if it fails...try to initialize the "line" variable before the foreach.

            • 3. Re: how to append the csv file
              mattboren Master
              vExpert

              Hello, td_sk-

               

              You shuold be able to use the function way that GuilhermeStela suggested.  Or, you could make a bit of an update to your existing code so that the Export-Csv call is outside of the foreach statement, so that it writes to CSV all the data in one operation.  Something like:

               

              Add-PSSnapin VMware.VimAutomation.Core
              Connect-VIServer 192.168.1.125

              ##VMname.csv having list of vms ####
              $vm = Import-csv c:\scripts\vmname.csv
              &{
              foreach ($line in $vm) {
                 
              Get-Datastore -VM $line.name | Select-Object @{n="VMName"; e={$line.name}},name,FreeSpaceGB
              }} |
              Export-Csv c:\scripts\ds.csv -NoTypeInformation    ## moved the Export-Csv outside of the foreach loop

               

              How does that do for you?  By the way, that "$line.name" portion of your original Select-Object statement probably needs to change (as done in the code here).