Author Posts

August 26, 2016 at 1:40 am

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

  • This topic was modified 2 years ago by  J J.

August 26, 2016 at 2:36 am

You will need to prefix your $Output and $CPUPercent variables inside the script block with Using: to tell the PowerShell engine to inject the value. I am assuming you are running PowerShell v3 or later.

From:
Out-File $Output -Append

To:
Out-File $Using:Output -Append

From:
Select-Object -Property Name, CPU, $CPUPercent, Description

To:
Select-Object -Property Name, CPU, $Using:CPUPercent, Description

Complete example:

$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, $Using:CPUPercent, Description | 
            Sort-Object -Property CPUUsed -Descending | Select-Object -First 15 | 
            Format-Table -AutoSize | Out-File $Using:Output -Append
    }
}

P.S.:
You will run into another problem with your script. At the end of the pipeline in your Invoke-Command you are formatting a table and writing it to a file. The whole script block including those commands will be executed on the remote servers. Meaning the Result.txt will not be created or appended on your Admin workstation/server. The file will get created on each remote server which you probably do not want.