How to Efficiently Retrieve and Save Drive Types Using PowerShell

Efficient management of hardware resources is crucial for IT professionals and Managed Service Providers (MSPs). One task that often arises is identifying the types of drives installed in a system.

Whether distinguishing between SSDs and HDDs or logging drive details for inventory purposes, having a reliable method to retrieve and save this information is invaluable. This blog post explores a PowerShell script designed for this purpose, explaining its functionality, potential use cases, and best practices.

Background

IT professionals frequently need to gather hardware details for various reasons, such as performance monitoring, inventory management, and troubleshooting. The provided PowerShell script is tailored to retrieve information about fixed drives, specifically Solid State Drives (SSDs) and Hard Disk Drives (HDDs), and save the results to a custom field.

This script is particularly useful in environments where automation and precision are critical, offering a streamlined solution to a common administrative task.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Get the drive types of all fixed SSD and HDD drives.
.DESCRIPTION
    Gets the drive types of all fixed SSD and HDD drives and can save the results to a custom field.

.EXAMPLE
    (No Parameters)
    ## EXAMPLE OUTPUT WITHOUT PARAMS ##
    DiskNumber DriveLetter MediaType BusType SerialNumber
    ---------- ----------- --------- ------- ------------
    0          C:          SSD       SATA    50026B768B3A4E3A
    1          D:          HDD       SATA    WD-WCC4N0JYJYJY

PARAMETER: -CustomFieldParam "ReplaceMeWithAnyMultilineCustomField"
    The name of the custom field to save the results to.
.EXAMPLE
    -CustomFieldParam "ReplaceMeWithAnyMultilineCustomField"
    ## EXAMPLE OUTPUT WITH CustomFieldParam ##
    DiskNumber DriveLetter MediaType BusType SerialNumber
    ---------- ----------- --------- ------- ------------
    0          C:          SSD       SATA    50026B768B3A4E3A
    1          D:          HDD       SATA    WD-WCC4N0JYJYJY
    [Info] Saving the results to the custom field. (ReplaceMeWithAnyMultilineCustomField)
    [Info] The results have been saved to the custom field. (ReplaceMeWithAnyMultilineCustomField)

Custom Field Output:
    #0, Letter: C:, Media: SSD, Bus: SATA, SN: 50026B768B3A4E3A
    #1, Letter: D:, Media: HDD, Bus: SATA, SN: WD-WCC4N0JYJYJY

.PARAMETER CustomFieldName
    The name of the custom field to save the results to.
.INPUTS
    None
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10/Server 2016
    Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$CustomFieldName
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if ($env:customFieldName -and $env:customFieldName -ne 'null') {
        $CustomFieldName = $env:customFieldName
    }

    # Get the drive type of all drives
    $Disks = Get-PhysicalDisk | Where-Object { $_.BusType -notlike "File Backed Virtual" -and -not ($_.PhysicalLocation -like "*USB*" -or $_.BusType -like "*USB*") } | Select-Object -Property DeviceID, MediaType, BusType, SerialNumber
    if ($($Disks | Where-Object { $_.MediaType -like "Unspecified" }).Count) {
        Write-Host "[Info] An Unspecified MediaType likely indicates this machine is a VM or there is an issue with that drive."
    }
    # Get the partitions with mounted drive letters
    $Partitions = Get-Partition | Where-Object { $_.DriveLetter -ne $null } | Select-Object -Property DriveLetter, DiskNumber
    # Join the two collections
    $Drives = $Disks | ForEach-Object {
        $Disk = $_
        $Partition = $Partitions | Where-Object { $_.DiskNumber -eq $Disk.DeviceID }
        [PSCustomObject]@{
            DiskNumber   = $_.DeviceID
            DriveLetter  = $Partition.DriveLetter | Where-Object { $_ }
            MediaType    = $_.MediaType
            BusType      = $_.BusType
            SerialNumber = $_.SerialNumber
        }
    }
    $($Drives | Out-String) | Write-Host

    # Save the results to a custom field
    if ($CustomFieldName) {
        Write-Host "[Info] Saving the results to the custom field. ($CustomFieldName)"
        $CustomField = $(
            $Drives | ForEach-Object {
                "#:$($_.DiskNumber), Letter: $($_.DriveLetter), Media: $($_.MediaType), Bus: $($_.BusType), SN: $($_.SerialNumber)"
            }
        ) | Ninja-Property-Set-Piped -Name $CustomFieldName 2>&1
        if ($CustomField.Exception) {
            Write-Host $CustomField.Exception.Message
            Write-Host "[Error] Failed to save the results to the custom field. ($CustomFieldName)"
        }
        else {
            Write-Host "[Info] The results have been saved to the custom field. ($CustomFieldName)"
        }
    }
}
end {
    
    
    
}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

Let’s break down the script step-by-step to understand its functionality and how it achieves its goal.

Prerequisites

The script requires PowerShell version 5.1 or higher. It begins by defining a .SYNOPSIS and .DESCRIPTION, providing an overview of its purpose. The .EXAMPLE sections demonstrate expected outputs with and without the -CustomFieldParam.

Parameters and Initial Setup

The script accepts a parameter, CustomFieldName, which specifies the name of the custom field where the results will be saved. It also includes a Test-IsElevated function to check if the script is running with Administrator privileges, which is necessary for accessing detailed drive information.

Processing Drive Information

  1. Elevated Privileges Check: The script first verifies if it is running with the necessary privileges. If not, it terminates with an error message.
  2. Environment Variable Handling: If a custom field name is set via an environment variable, it overrides the script parameter.
  3. Drive Information Retrieval: Using Get-PhysicalDisk, the script retrieves all physical drives, filtering out virtual and USB drives. It then selects relevant properties: DeviceID, MediaType, BusType, and SerialNumber.
  4. Partition Information: The script fetches partition details using Get-Partition, focusing on partitions with assigned drive letters.
  5. Data Aggregation: It merges the physical drive and partition information, creating a comprehensive list of drives with their respective details.

Output and Custom Field Saving

The script outputs the drive information to the console. If a CustomFieldName is provided, it formats the data and attempts to save it to the specified custom field using a hypothetical cmdlet Ninja-Property-Set-Piped. It handles potential errors during this process and provides feedback on the operation’s success.

Potential Use Cases

An MSP manages multiple client systems, needing to regularly audit hardware configurations to ensure optimal performance and identify potential issues.

By deploying this script across client machines, the MSP can automate the collection of drive types and log the data for future reference. This allows for quick identification of systems that might benefit from hardware upgrades, such as replacing an HDD with an SSD for improved performance.

Comparisons

Compared to manual methods or using disparate tools, this script offers a unified approach within the PowerShell environment, reducing the need for external applications. While tools like Windows Management Instrumentation (WMI) or third-party software can achieve similar results, this script’s integration with custom fields and its automation capabilities make it a more efficient and scalable solution.

FAQs

  1. Do I need administrative privileges to run this script? Yes, the script requires administrative privileges to access detailed drive information.
  2. Can this script be used on virtual machines? The script may not provide accurate results on virtual machines as the MediaType can be listed as “Unspecified.”
  3. What happens if the custom field name is not provided? If the CustomFieldName parameter is not specified, the script will only output the drive information to the console.

Implications

Regularly auditing drive types can have significant implications for IT security and performance. For instance, identifying older HDDs allows for proactive replacements, reducing the risk of data loss due to drive failure. Additionally, understanding the storage architecture can aid in optimizing backup strategies and ensuring that critical data is stored on the most reliable hardware.

Recommendations

  • Always run the script with elevated privileges.
  • Regularly schedule the script to run across all managed systems to maintain up-to-date hardware inventories.
  • Ensure proper error handling and logging mechanisms are in place to troubleshoot any issues during execution.

Final Thoughts

This PowerShell script offers a robust solution for IT professionals and MSPs to retrieve and save drive types efficiently. By automating this process, organizations can maintain accurate hardware inventories, optimize performance, and enhance their overall IT management strategies.

Tools like NinjaOne can further streamline this process by integrating such scripts into broader automation workflows, providing a comprehensive IT management platform that supports proactive and efficient operations.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).