众所周知,我们可以Get-Counter
而不是提供计数器的路径,例如Get-Counter "\\Processor(_Total)\% Processor Time")
所以现在我想用变量作为路径做同样的事情:
$myPath = "[THIS IS MY PATH]"
$metricValue = [int] ((Get-Counter $myPath).countersamples | select -property
cookedvalue).cookedvalue
不幸的是我收到以下错误:
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
所以我不能在Get-Counter
之后为路径添加变量,但我需要这样做!
有解决办法吗?
答案 0 :(得分:3)
以下在我的电脑上运行良好
$myPath="\\johns-pc\processor(_total)\% processor time"
$metricValue=[int]((Get-Counter($myPath)).countersamples | select -property cookedvalue).cookedvalue
答案 1 :(得分:1)
将命令构造为String,如下所示:
$metricValueString = "[int] ((Get-Counter $myPath).countersamples | select -property cookedvalue).cookedvalue"
使用Invoke-Expression
执行它$metricValue = Invoke-Expression $metricValueString
此致
**修复了破碎的代码行