如何使用变量在PowerShell中调用Get-Counter

时间:2014-01-10 20:37:16

标签: powershell

众所周知,我们可以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之后为路径添加变量,但我需要这样做!

有解决办法吗?

2 个答案:

答案 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

此致

**修复了破碎的代码行