Link to home
Create AccountLog in
Avatar of Robert Perez-Corona
Robert Perez-CoronaFlag for United States of America

asked on

PoSh function to get CPU utilization from remote machine

I have a one-liner I need to turn into a function so that I can run against any machine on my AD domain/network. For example, instead of modifying the computername parameter and running the line can I execute something like:

Get-CPU -computername MYREMOTESERVER

Get-WmiObject -computername MYREMOTESERVER win32_processor | Measure-Object -property LoadPercentage -Average | Select Average

Thank you in advance
Avatar of J0rtIT
J0rtIT
Flag of Venezuela, Bolivarian Republic of image

function Get-CPU{
    [Cmdletbinding()]
    parameter(
        [parameter(mandatory=$true, position=0)]$remoteserver
    )
    Process{
        $result=Get-WmiObject -computername $remoteserver win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
    }
    end{
        return $result
    }
}

Open in new window

We want to stay with the common naming conventions, Jose, and the asker correctly asked for a parameter ComputerName,  so $remoteserver should be replaced by $ComputerName.
Also the process technique is oversized here, and even counterproductive as it will not allow proper pipeline processing of the result.

I think a much simpler approach is much better here
function Get-CPU ([String] $ComputerName = $env:ComputerName)
{
  Get-WmiObject -computername $ComputerName win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
I agree that is much better  - and contains the respective computername in the output, which is missing from the former suggestions ;-).
Avatar of Robert Perez-Corona

ASKER

thank you all