Getting Machine Disk Information in PowerShell

This sample creates a PowerShell function that lists details about disk drives on a machine. By default it will list details about all drives, but you can also supply a specific drive name:

                                        
  Function Get-DiskDetails([string] $driveName) {
    
    # Get Wmi object for disk information
    $result = Get-WmiObject win32_logicaldisk

    # If a drive name was specified, filter out other drives
    if($driveName)
    {
        $result = $result | ?{$_.DeviceID -eq $driveName}
    }

    #
    # List info about each drive in the result
    #
    $counter = 1
    $result | %{
      Write-Host "$($counter).)"
      Write-Host "Drive: $($_.DeviceID)"
      Write-Host "Description: $($_.Description)"
      Write-Host "Capacity: $($_.Size)"
      Write-Host "Free Space: $($_.FreeSpace)`n"

      $counter++
    }
  }

                                        

Examples of using this sample:

                                        
 Get-DiskDetails

 1.)
 Drive: C:
 Description: Local Fixed Disk
 Capacity: 255953203200
 Free Space: 76167348224

 2.)
 Drive: D:
 Description: CD-ROM Disc
 Capacity: 
 Free Space: 

 3.)
 Drive: E:
 Description: Removable Disk
 Capacity: 
 Free Space: 

 Get-DiskDetails C:

 1.)
 Drive: C:
 Description: Local Fixed Disk
 Capacity: 255953203200
 Free Space: 76167348224


                                        

This function uses a couple of alias that are worth noting. The first is "?" which corresponds to Where-Object and the other is "%" which is an alias for Foreach-Object. These two cmdlets are used frequently so it's a good idea to learn the alias for them.


© 2024 Embrs.net