Function: Get-ComputerDetails

PowerShell for Admins

Another nice addition for today. In the 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
    $result = @()
    foreach ($node in $Computer)
            $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
            Write-Error -Message "The command failed for computer $node. Message: $_.Exception.Message"
        $result += $customObject

To use it:

Get-ComputerDetails -Computer or01,dc01,ipam01

10 Responses to " Function: Get-ComputerDetails "

  1. Jaap Brasser says:

    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. Steve G says:

    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, what exactly are you trying to do? Do you start a PowerShell console, paste in the code, and then try to use the code?

    • Don Jones says:

      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.

    • Steve G says:

      You mentioned ‘dot sourcing’, so I looked that up. That seems to have worked. Learn something new everyday.

  3. Why make multiple calls to win32_ComputerSystem ?
    make one call, store the result then populate your object from that. Much more efficient

  4. Also – wasn’t [CmdletBinding()] introduced with PowerShell 2.0 in which case your #requires would need altering

    • 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