Search code examples
powershell-2.0powershell-remoting

Limit of an individual PowerShell command


I am running below script to get CPU utilization from multiple servers.However there are a couple of computers I have come across where the below script just sticks forever i.e. no error, no console output. So I have used Job command to kill after specific time period. But when am trying to execute this code am getting below error.

Is there a way to set a time limit of an individual PowerShell command?

$ServerList = ("xyz","abc")
foreach ($computername in $ServerList) {
    $timeout = 30
    $job = Start-Job -ScriptBlock {
        Get-WmiObject Win32_Processor -ComputerName $using:computername |
            Measure-Object -Property LoadPercentage -Average |
            Select Average
    }
    Wait-Job -Job $job -Timeout $timeout
    Stop-Job -Job $job
    Receive-Job $job
    Remove-Job -Job $job
}
Cannot validate argument on parameter 'ComputerName'. The argument is null or
empty. Supply an argument that is not null or empty and then try the command
again.
    + CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Solution

  • Sorry, I had missed that you're using PowerShell v2. The using: scope modifier isn't available prior to PowerShell v3, so you need to use the the -ArgumentList parameter for passing the computer name into the scriptblock.

    Change this:

    $job = Start-Job -ScriptBlock {
        Get-WmiObject Win32_Processor -ComputerName $using:computername |
            Measure-Object -Property LoadPercentage -Average |
            Select Average
    }

    into this:

    $job = Start-Job -ScriptBlock {
        Get-WmiObject Win32_Processor -ComputerName $args[0] |
            Measure-Object -Property LoadPercentage -Average |
            Select -Expand Average
    } -ArgumentList $computername