Function: Get-ComputerDetails

Another nice addition for today. In the Powershell.org forums someone asked for retrieving computer information. This information is being retrieved from several WMI objects, and had to be combined in the results. For this PowerShell custom objects are the perfect fit.

The code:

#requires -Version 1
Function Get-ComputerDetails
{
    [cmdletbinding()]
    Param([string[]]$Computer)
    
    $result = @()

    foreach ($node in $Computer)
    {
        try
        {
            $customObject = [pscustomobject][ordered]@{
                Name         = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $node -ErrorAction Stop).Name
                Manufacturer = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $node -ErrorAction Stop).Manufacturer
                Model        = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $node -ErrorAction Stop).Model
                Serial       = (Get-WmiObject -Class Win32_Bios -ComputerName $node -ErrorAction Stop).SerialNumber
            }
        }
        catch 
        {
            Write-Error -Message "The command failed for computer $node. Message: $_.Exception.Message"
            break
        }
        $result += $customObject
    }
    $result
}

To use it:

Get-ComputerDetails -Computer or01,dc01,ipam01

About the Author

Richard Diphoorn

I'm a autobot. DevOps & Automation are the future. PowerShell Addict. Make it so lover.

10 Comments

  1. Maybe get rid of the $CustomObject and $result variable as they don't serve any purpose. Just create the object and let the PowerShell deal with the output.

  2. I've tried to use this function. It will run nicely and I can use it - but ONLY from the Windows PowerShell ISE embedded powershell window. This will NOT create a function in ANY other PowerShell process.

    Any ideas on why this might be the case?

    Steve G.

    • Steve, are you just running the script in the console? That won't define a "permanent" function - due to scoping, the function "disappears" when the script finishes. You'll want to either dot-source the script, or add the function to a Script Module that you can load into the shell. It works in ISE because ISE has a slightly different scope behavior to facilitate development.

    • Mike also notified me on this, and this was my reply to him:

      The "required" line actually comes from the refactoring functionality in ISESteroids; looks like a bug to me that it doesn't recognise what you described. I will report it back to Tobias Weltner.

      Thanks for noticing. I've updated the function and posted it again here: Link