Get free disk space from remote computers

free disk space

One of the things that you have to monitor in your environment is free disk space. In this short article I want to share with you some code lines which help to create disk report.

Free disk space

Script is based on Get-WmiObject cmdlet which gets instances of Windows Management Instrumentation (WMI) classes or information about the available WMI classes. For more information please refer to Microsoft docs page.

Script will check free space on "C:","D:","E:" partitions. Using Switch you can change description of disk partition:

                    $Drives = "C:","D:","E:"

                    Switch ($Letter)
                    {
                        "C:"     { $Val = "OSDDisk (C:)"}
                        "D:"     { $Val = "Data (D:)"}
                        "E:"     { $Val = "Mountpoint_log (E:)"}
                    }

Final script:

    $Servers = Get-Content "C:\users\$env:username\desktop\input.txt" 
    $Drives = "C:","D:","E:"

    $report = @()

    #Looping each server
    Foreach($Server in $Servers)
    {
        $Server = $Server.trim()
        Write-Host "Processing $Server" -ForegroundColor Green
        Try
        {
            $Disks = Get-WmiObject -Class win32_logicaldisk -ComputerName $Server -ErrorAction Stop
        }
        Catch
        {
            $_.Exception.Message
            Continue
        }    
            If(!$Disks)
            {
                Write-Warning "Something went wrong"
            }
            Else
            {
                # Adding properties to object
                $Object = New-Object PSCustomObject
                $Object | Add-Member -Type NoteProperty -Name "ServerName" -Value $Server
            
                Foreach($Letter in $Drives)
                {
                    Switch ($Letter)
                    {
                        "C:"     { $Val = "OSDDisk (C:)"}
                        "D:"     { $Val = "Data (D:)"}
                        "E:"     { $Val = "Mountpoint_log (E:)"}
                    }

                    $FreeSpace = ($Disks | Where-Object {$_.DeviceID -eq "$Letter"} | Select-Object @{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}).freespace 
                    If($FreeSpace)
                    {
                        $Value = "$Freespace" + " GB"
                        $Object | Add-Member -Type NoteProperty -Name "$Val" -Value $Value    
                    }
                    Else
                    {
                        $Object | Add-Member -Type NoteProperty -Name "$Val" -Value "(not found)" 
                    }
                }
                $report += $object
            }
    } 

    #Display results
    return $report

    #Save results to CSV file
    $report | Export-Csv -Path C:\users\$env:username\desktop\free_space.csv -NoTypeInformation -Force

Leave a Reply

Your email address will not be published. Required fields are marked *