0

I'm using the following script to try and ping a list of computers stored in a CSV. The desired outcome is that I'll be able to verify the timeout condition.

$servers = ipcsv "\\testbox\c$\Tools\PAL Stuff\servers.csv"
$timeoutSeconds = 3
$code = {
  foreach($server in $servers) {
    $name = $server.name
    if($ping = Test-Connection -ComputerName $($args[0]) -BufferSize 16 -quiet -count 30) {
      write-host "This should be 30 pings."
    } else {
      write-host "This should display when the job times out"
    }
  }
} -ArgumentList $name
$j = Start-Job -ScriptBlock $code 
if (Wait-Job $j -Timeout $timeoutSeconds) { Receive-Job $j }
Remove-Job -force $j

This script results in an error:

You must provide a value expression on the right-hand side of the '-' operator."

If I move the Argument List to here:

$j = Start-Job -ScriptBlock $code -ScriptBlock $code

I get an error that it

could not validate argument on parameter 'ComputerName'. The argument is null or empty.

I've seen articles and questions on passing variables to the scriptblock, but they're for Invoke-Command and not Start-Job, and I have yet to get it work in translation. I'm under the impression that if it worked, I wouldn't see the output that I'm expecting, which is the Write-Host.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 2
    Your question doesn't make much sense as it is. You want to start a job that supposedly times out after 3 seconds, but do 30 pings inside the job for every computer on your list, which takes about 30 seconds each. Also, you're querying the list of computers sequentially (loop inside the job) rather than in parallel (jobs inside a loop), which would make more sense. Please take a step back and describe the problem you're trying to solve with your code rather than what you perceive as the solution. – Ansgar Wiechers Jun 02 '15 at 13:40
  • Thank you for your answer, it helps. I obviously don't know how to work with jobs. I had put that in my question originally, I'm not sure how it wound up being removed. I'll keep googling for the answer and figure it out eventually. – user1628184 Jun 02 '15 at 15:58
  • 1
    You say you want to verify a timeout condition for all hosts, so what is this condition actually? The 30 pings or the 3 seconds? Also, how many hosts do you have? For a small number of hosts sequential checks are easier to handle, but for a large number running the checks in parallel is mandatory unless you want to wait until forever. These details allow us to come up with more helpful answers. – Ansgar Wiechers Jun 02 '15 at 17:34

0 Answers0