Script to get CPU Usage

后端 未结 1 408
臣服心动
臣服心动 2021-01-23 01:51

I am using this script to get CPU usage from multiple server

$Output = \'C:\\temp\\Result.txt\'
$ServerList = Get-Content \'C:\\temp\\Serverlist.txt\'
$CPUPercen         


        
相关标签:
1条回答
  • 2021-01-23 02:16

    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.

    0 讨论(0)
提交回复
热议问题