Search code examples
arrayspowershellstatisticsstoragespace

Powershell | Script that Analysis Used and Free Storage of Servers and than exports it to an CSV


i need to create an Script that checks the Free and Used storages of Hosts within our Network. The Hosts are loaded into an array and than those disks with Free Space and Size are being shown in the PowerShell. Now i want that all of those things are being exported to an csv File so you can analyse the data easier.

Here is the script:

$servers = @("server1", "server2", "server3")

Foreach ($server in $servers)
{
    $disks = Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter DriveType=3 | 
        Select-Object DeviceID, 
            @{'Name'='Size'; 'Expression'={[math]::truncate($_.size / 1GB)}}, 
            @{'Name'='Freespace'; 'Expression'={[math]::truncate($_.freespace / 1GB)}}

    $server

    foreach ($disk in $disks)
    {
        $disk.DeviceID + $disk.FreeSpace.ToString("N0") + "GB / " + $disk.Size.ToString("N0") + "GB"
        

     }
 }
 

Thx btw :)


Solution

  • Instead of trying to control the output format by manually outputting the $server value, you'll want to "glue" the server name onto each associated $disk object, this will make it much easier to export to CSV (with the correct server name):

    $servers = @("server1", "server2", "server3")
    
    $allDisks = foreach ($server in $servers)
    {
        # Instead of assigning to `$disks` inside the loop, 
        # we let the output from all loop executions "bubble up" 
        # to the assignment to `$allDisks`
        Get-WmiObject Win32_LogicalDisk -ComputerName $server -Filter DriveType=3 | 
            Select-Object @{'Name'='ComputerName'; 'Expression'={$server}},
                DeviceID, 
                @{'Name'='Size'; 'Expression'={[math]::truncate($_.size / 1GB)}}, 
                @{'Name'='Freespace'; 'Expression'={[math]::truncate($_.freespace / 1GB)}}
    }
    

    Now that each object has the correct server name attached, we can easily export to CSV:

    $allDisks |Export-Csv .\path\to\output.csv -NoTypeInformation
    

    ... and we can also use PowerShell's native formatting subsystem for manipulating the output in the interactive shell nicely:

    $allDisks |Format-Table DeviceID,Size,FreeSpace -GroupBy ComputerName