Blademoon
Blademoon

Reputation: 109

How to properly pass a Win32 class object to a function

I try to write script (PowerShell) that return CPU name using Win32:

$temp = Get-WmiObject Win32_Processor

$temp.Name

function Get-CPU-Name {
    [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][System.Management.ManagementBaseObject]$Temp1
    return $Temp1.Name
}

Get-CPU-Name

A function call should return the name of the processor, but it does not return anything. How to correctly pass a variable with the results of the "Get-WmiObject Win32_Processor" command to the function

Upvotes: 2

Views: 150

Answers (1)

Theo
Theo

Reputation: 61198

You're almost there, but forgot to put the parameter inside param(..).

This should work:

function Get-CPU-Name { 
    param (
        [parameter(Mandatory=$true, Position = 0)]
        [System.Management.ManagementBaseObject]$Temp1
    )
    $Temp1.Name
}

Get-CPU-Name (Get-WmiObject Win32_Processor)

Upvotes: 2

Related Questions