Script to get CPU Usage

限于喜欢 提交于 2019-12-02 01:17:14

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
}

Please also notice that I moved the definition of $CPUPercent into the script block as this suffered from the same problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!