Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用变量在PowerShell中调用Get计数器_Powershell - Fatal编程技术网

如何使用变量在PowerShell中调用Get计数器

如何使用变量在PowerShell中调用Get计数器,powershell,Powershell,众所周知,我们可以执行Get Counter,然后提供计数器的路径,例如Get Counter“\\Processor(\u Total)\%Processor Time”) 现在我只想用一个变量作为路径做同样的事情: $myPath = "[THIS IS MY PATH]" $metricValue = [int] ((Get-Counter $myPath).countersamples | select -property cookedvalue).cookedva

众所周知,我们可以执行
Get Counter
,然后提供计数器的路径,例如
Get Counter“\\Processor(\u 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:被调用的实例在[Path]+上不可用

$metricValue=[int]((Get Counter将命令构造为如下字符串:

 $metricValueString = "[int] ((Get-Counter $myPath).countersamples | select -property cookedvalue).cookedvalue"
并使用Invoke表达式执行它

$metricValue = Invoke-Expression $metricValueString
问候


**修复了代码的虚线

将命令构造为如下字符串:

 $metricValueString = "[int] ((Get-Counter $myPath).countersamples | select -property cookedvalue).cookedvalue"
并使用Invoke表达式执行它

$metricValue = Invoke-Expression $metricValueString
问候


**修复了代码的虚线

以下代码在我的计算机上运行良好

$myPath="\\johns-pc\processor(_total)\% processor time"
$metricValue=[int]((Get-Counter($myPath)).countersamples | select -property cookedvalue).cookedvalue

在我的计算机上,以下各项工作正常

$myPath="\\johns-pc\processor(_total)\% processor time"
$metricValue=[int]((Get-Counter($myPath)).countersamples | select -property cookedvalue).cookedvalue

很好的技巧谢谢分享!上面约翰的答案有点干净,所以我把它标记为答案。很好的技巧谢谢分享!上面约翰的答案有点干净,所以我把它标记为答案。