locked
output powershell to csv RRS feed

  • Question

  • I've got a script to get free space of all servers in a domain. This works great. Here's the script:

    clear 
    $cre = get-Credential # This user account should be Adminstrator  
    $file = get-Content C:\Users\wduizer\Desktop\servers.txt  # Replace it with your TXT file which contain Name of Computers  
     
    foreach ( $args in $file) { 
    get-WmiObject win32_logicaldisk -Credential $cre -ComputerName $args -Filter "Drivetype=3"  |  
    ft SystemName,DeviceID,VolumeName,@{Label="Total SIze";Expression={$_.Size / 1gb -as [int] }},@{Label="Free Size";Expression={$_.freespace / 1gb -as [int] }} -autosize
     }

    but now i want to export the result to a csv file so i can come up with a weekly report and save it in to a hystory database.

    I cant seem to find a way to simply export the result as shown on screen to a file i'll get either the whole proces with get-process or i'll get only a file of the last server in the list with export-csv...

    Can anyone help me ? 

    Tuesday, June 16, 2015 5:33 PM

Answers

  • Hi Wim,

    You have to use the parameter -append to add the output to the end of an existing file, instead of replacing the file contents.

    https://technet.microsoft.com/en-us/library/hh849882.aspx  

    foreach ( $args in $file) { 
    get-WmiObject win32_logicaldisk -Credential $cre -ComputerName $args -Filter "Drivetype=3"  |  
    ft SystemName,DeviceID,VolumeName,@{Label="Total SIze";Expression={$_.Size / 1gb -as [int] }},@{Label="Free Size";Expression={$_.freespace / 1gb -as [int] }} -autosize | Out-File C:\output.csv -append
     }

    • Marked as answer by Wim Duizer Tuesday, June 16, 2015 8:04 PM
    Tuesday, June 16, 2015 7:56 PM

All replies

  • Hi,

    I only have one machine right now, but addingOut-File C:\output.csv to your script (after autosize) gave me the exact same result as in the PS console.


    Best regards, Kjetil :) Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.

    Tuesday, June 16, 2015 5:46 PM
  • piping into out-file wil only give back the last server results like i'll get from the export-csv command...
    Tuesday, June 16, 2015 7:40 PM
  • Hi Wim,

    You have to use the parameter -append to add the output to the end of an existing file, instead of replacing the file contents.

    https://technet.microsoft.com/en-us/library/hh849882.aspx  

    foreach ( $args in $file) { 
    get-WmiObject win32_logicaldisk -Credential $cre -ComputerName $args -Filter "Drivetype=3"  |  
    ft SystemName,DeviceID,VolumeName,@{Label="Total SIze";Expression={$_.Size / 1gb -as [int] }},@{Label="Free Size";Expression={$_.freespace / 1gb -as [int] }} -autosize | Out-File C:\output.csv -append
     }

    • Marked as answer by Wim Duizer Tuesday, June 16, 2015 8:04 PM
    Tuesday, June 16, 2015 7:56 PM