如何使用变量在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
很好的技巧谢谢分享!上面约翰的答案有点干净,所以我把它标记为答案。很好的技巧谢谢分享!上面约翰的答案有点干净,所以我把它标记为答案。