V T V T - 3 months ago 26
PowerShell Question

Script to get CPU Usage

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
}
}


and I am getting error


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...?

Answer

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.

Comments