Returning custom objects in PowerShell, simplified

I’ve stumbled upon this simplified technique to return custom objects in my PowerShell functions.

My first take on it was this, but I’ve simplified it. In this simplified variation, you just create and return the object in the same hash. For example:

[PsCustomObject]@{
    ComputerName = $ComputerSystem.DNSHostName;
    Domain = $ComputerSystem.Domain;
    ProcessCount = $ProcessCount;
    }

This is a hash, as you probably have seen before, but the [PsCustomObject] is what makes it a custom object.

And in context of a function:

# Example Function
function Get-SystemInfo {

    # Prepare the info
    $OS = Get-CimInstance -ClassName Win32_OperatingSystem # for FreePhysicalMemory, Caption, PSComputerName, SystemDrive
    $LoadPercentage = (Get-CimInstance -ClassName Win32_Processor).LoadPercentage
    $ProcessCount = (Get-Process).Count
    $SystemDrive = Get-CimInstance -ClassName Win32_LogicalDisk -filter "Name = '$($OS.SystemDrive)'" 
    $ComputerSystem = Get-CimInstance -ClassName Win32_ComputerSystem

    # Return the properties in a custom object
    [PsCustomObject]@{
        ComputerName = $ComputerSystem.DNSHostName;
        Domain = $ComputerSystem.Domain;
        FreePhysicalMemory = "{0:n0}" -f ($OS.FreePhysicalMemory /1KB) + " MB";
        OS = $OS.Caption;
        LastBootUpTime = $OS.LastBootUpTime;
        LoadPercentage = $LoadPercentage;
        ProcessCount = $ProcessCount;
        SysVolFree = "{0:n1}" -f ($SystemDrive.FreeSpace /1GB) + " GB"
        }
     
    }

# Example Usage

# Using the results, put them into an object "$Result"
$Result = Get-SystemInfo

# Access the values inside the object
$Result.LastBootUpTime

Leave a Reply

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