0
votes

I have a question. Im making a port scanner and i want to make jobs for every port it scans if its open or not.

$endport = 100
$timeout = 100
$ipadres = "192.168.0.137" 

$testPort = { 
Param($port)
    $tcpClient.ConnectAsync($ipadres, $port).Wait($timeout)
} 


For($i=1; $i -le $endport; $i++) {
    Start-Job -scriptblock $testPort -ArgumentList $i 
}
Get-Job | Wait-Job 
$out = Get-Job | Receive-Job 
$out

So in this example i want to scan the ip adress 192.168.0.137 from port 1 to 100. But when i run this and show the result of my job i get this error

You cannot call a method on a null-valued expression.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    + PSComputerName        : localhost

Does anybody have an idea how i can solve this?

1
Is $tcpClient initialized? - Jesse
Oh god, what a stupid of me... Thanks though! - Thomas Van Raemdonck

1 Answers

0
votes

Although you find out the issue in comments, just a quick note - using jobs in your case is really overkill. Each job will create child process and will eat few MB of your memory. You already using task (by calling Async method), so just stick with it. For example



$tasks = foreach($i in 1..100) {
  $tcpClient = [System.Net.Sockets.TcpClient]::new()
  $tcpClient.ConnectAsync($ipadres, $i)
 }

[System.Threading.Tasks.Task]::WaitAll($tasks)

$tasks | select id,  status, result | format-table