0

As we all know we can do Get-Counter and than provide the path to the counter, e.g., Get-Counter "\\Processor(_Total)\% Processor Time")

So now I want to do the same thing only then with a variable as path:

$myPath = "[THIS IS MY PATH]"           
$metricValue = [int] ((Get-Counter $myPath).countersamples | select -property
cookedvalue).cookedvalue

Unfortunately I get the following error:

Get-Counter : The called instance is not available    At [Path]    +            
$metricValue = [int] ((Get-Counter <<<<  -Counter $myPath).countersamples |

select -property cookedvalue).cookedvalue
    + CategoryInfo          : InvalidResult: (:) [Get-Counter], Exception
    + FullyQualifiedErrorId : 
        CounterApiError,Microsoft.PowerShell.Commands.GetCounterCommand

So I cannot put a variable after Get-Counter for the path, but I need to do that!

Is there a solution to do so?

2 Answers 2

3

The following worked fine on my computer

$myPath="\\johns-pc\processor(_total)\% processor time"
$metricValue=[int]((Get-Counter($myPath)).countersamples | select -property cookedvalue).cookedvalue
Sign up to request clarification or add additional context in comments.

Comments

1

Construct your command as a String like this:

 $metricValueString = "[int] ((Get-Counter $myPath).countersamples | select -property cookedvalue).cookedvalue"

And execute it using Invoke-Expression

$metricValue = Invoke-Expression $metricValueString

Regards

** fixed broken line of code

1 Comment

Nice trick thanks for sharing! Answer of John above is a bit cleaner so I marked that as answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.