获取计数器

时间:2016-09-08 18:04:45

标签: powershell

Is there any way to use Credentials parameter with get-counter?

我尝试了下面的代码,但它没有用。我在这里使用的是一个本地用户帐户,它在目标服务器上具有管理员权限。

Invoke-Command -Computername XXXX -ScriptBlock {(get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5 | select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average} -Credential XXXX\YYYY

1 个答案:

答案 0 :(得分:0)

文档说Nope

根据您的代码判断,您尝试将用户名和密码作为字符串提供给凭证参数,但这不是它的工作原理。您必须创建一个凭证对象,如下所示:

$secpasswd = ConvertTo-SecureString “PlainTextPassword” -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“username”, $secpasswd)

之后,您可以拨打Invoke-Command并提供$mycreds作为凭据:

Invoke-Command -Computername XXXX -ScriptBlock {(get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5 | select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average} -Credential $mycreds

如果您正确提供凭据但仍然无效,您可以尝试再次使用Scriptblock中的Invoke-Command并在那里提供凭据。

您可以使用-Argumentlist参数将凭证对象作为参数传递给Scriptblock,并使用$args[0]在Scriptblock中访问它,或者在Scriptblock内部进行参数声明并通过声明的名称。

相关问题