获取CPU使用率的脚本 [英] Script to get CPU Usage
问题描述
我正在使用此脚本从多个服务器获取CPU使用情况
I am using this script to get CPU usage from multiple server
$Output = 'C:\temp\Result.txt'
$ServerList = Get-Content 'C:\temp\Serverlist.txt'
$CPUPercent = @{
Label = 'CPUUsed'
Expression = {
$SecsUsed = (New-Timespan -Start $_.StartTime).TotalSeconds
[Math]::Round($_.CPU * 10 / $SecsUsed)
}
}
Foreach ($ServerNames in $ServerList) {
Invoke-Command -ComputerName $ServerNames -ScriptBlock {
Get-Process | Select-Object -Property Name, CPU, $CPUPercent, Description | Sort-Object -Property CPUUsed -Descending | Select-Object -First 15 | Format-Table -AutoSize | Out-File $Output -Append
}
}
错误
无法将参数绑定到参数'FilePath',因为它为空。
+ CategoryInfo:InvalidData:(:) [Out-File],ParameterBindingValidationException
+ FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand
+ PSComputerName:ServerName
Cannot bind argument to parameter 'FilePath' because it is null. + CategoryInfo : InvalidData: (:) [Out-File], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand + PSComputerName : ServerName
您能在这方面帮助我吗?
Can you pls assist me in this...?
推荐答案
问题是您在脚本块中使用了 $ Output
,该脚本块是通过 Invoke-Command
,因此在远程会话中执行脚本块时未定义。
要修复该问题,可以将其作为参数传递给脚本块,或者在脚本块内定义它,但我想您宁愿在启动客户端上而不是在远程计算机上写入文件。因此,您可能不想在脚本块外使用 Out-File
,而是像这样
The problem is that you use $Output
in your script block which you invoke on the remote computer via Invoke-Command
and therefore is not defined when the script block is executed in the remote session.
To fix it you could pass it as parameter to the script block or define it within the script block but I guess you rather want to write the file on the initiating client rather than on the remote computer. So instead of using Out-File
in the script block you may want to use it outside the script block like so
$Output = 'C:\temp\Result.txt'
$ServerList = Get-Content 'C:\temp\Serverlist.txt'
$ScriptBlock = {
$CPUPercent = @{
Label = 'CPUUsed'
Expression = {
$SecsUsed = (New-Timespan -Start $_.StartTime).TotalSeconds
[Math]::Round($_.CPU * 10 / $SecsUsed)
}
}
Get-Process |
Select-Object -Property Name, CPU, $CPUPercent, Description |
Sort-Object -Property CPUUsed -Descending |
Select-Object -First 15
}
foreach ($ServerNames in $ServerList) {
Invoke-Command -ComputerName $ServerNames -ScriptBlock $ScriptBlock |
Out-File $Output -Append
}
请注意我将 $ CPUPercent
的定义移到了脚本块中,因为它遇到了同样的问题。
Please also notice that I moved the definition of $CPUPercent
into the script block as this suffered from the same problem.
这篇关于获取CPU使用率的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!