0

I have to write a Port Scanner for school, All look to work fine, but -ErrorAction Ignore doesnt work, errors are showing up.

function portScanner($xhost){
    $range=1..1024
    foreach($port in $range){
        $connection = New-Object System.Net.Sockets.TCPClient($xhost, $port) -ErrorAction Ignore
        if($connection.Connected){
            Write-Host "Port $port is open!" -ForegroundColor Magenta
        }
        elseif(!($connection.Connected)){
            Write-Host "Port $port is closed" -ForegroundColor Red
        }
    }
}


portScanner($env:COMPUTERNAME)





New-Object : Exception calling ".ctor" with "2" argument(s): "No connection could be made because the target machine actively refused it 192.168.10.10:1"
At C:\Users\Administrator\Documents\Untitled3.ps1:4 char:23
+ ... onnection = New-Object System.Net.Sockets.TCPClient($xhost, $port) -E ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
 
Port 1 is closed
mklement0
  • 382,024
  • 64
  • 607
  • 775
Shenladen
  • 19
  • 4
  • @boxdog `-EA 0` would not help in this case – Santiago Squarzon May 13 '22 at 13:55
  • 1
    @Empty_boy be careful with setting `$ErrorActionPreference`, since it will suppress any other errors – Cpt.Whale May 13 '22 at 14:04
  • In short: the `-ErrorAction` common parameter only acts on _non-terminating_ errors, whereas what your command (`New-Object`) generates is a (statement-)_terminating_ error. To act on or silence terminating errors, it's best to use a `try` / `catch` statement. See the [linked duplicate](https://stackoverflow.com/q/60541618/45375) for more information. – mklement0 May 13 '22 at 14:45

0 Answers0