ANy alternative to "Test-NetConnection" under Win7?

Hi mates, unfortunately this command doesn’t work on Win7, do you know any other solution?
I’ve tried to run this script, but it return always False (I’m sure my local 8000 port is open)

function Test-Port() {
try {
$client = New-Object Net.Sockets.TcpClient
$client.Connect(127.0.0.1, 8000)
Write-OUtput $True
}
catch {
Write-Output $false
}
finally {
$client.Dispose()
}
}

Test-Port

Thank you

The support for Windows 7 has ended. Migrate to a supported system please.

unfortunately the computer is very small with only 1GB of RAM, it has a Valid WIn7 license and I?m not going to pay to improve to Win10 with probably really slow results (only 1GB of RAM), I would kindly ask someone if there is a trick to overcome it. Maybe the script I wrote is correct but somehow don’t work for me, mayb I?m doing something wrongly.
Thank you for your sympathy

Have you tried the Get-NetTcpConnection cmdlet to accomplish your task? If that cmdlet is not available on your machine I have had success writing a simple PowerShell function to parse the netstat -ano command. I can give you some examples on how to go about that if need.

You don’t have to pay to upgrade the licence … it’s still free. And even for Windows 7 is 1GB everything else than good. :wink:

[quote quote=212394]Have you tried the Get-NetTcpConnection cmdlet to accomplish your task? If that cmdlet is not available on your machine I have had success writing a simple PowerShell function to parse the netstat -ano command. I can give you some examples on how to go about that if need.

[/quote]
Thank you! I would be glad to read your examples! Unfortunately Get-NetTcpConnection cmdlet is not available

The netstat -ano command will return current connections. In PS this will be an array of strings. The code below basically parses those strings and places the values into custom objects.

#This deals with IPV6 addresses
function ExtractPort ($address) {
if ($address -match "\[.*") {
$addr, $port = $address -split "\]:"
$addr + "]"
$port
} #if IPV6
else {$address -split ":"}
} #function

foreach ($connection in (netstat -ano)) {
#disregard header rows
If ($connection -notlike "*TCP*" -and $connection -notlike "*UDP*") {continue}
# Split the rows into fields and disregard headers
switch -wildcard ($connection)
{
'*TCP*' {$proto, $localaddress, $remoteaddress, $state, $process = -split $connection}
'*UDP*' {$proto, $localaddress, $remoteaddress, $process = -split $connection; $state = "STATELESS"}
} # switch
$localaddress, $localport = ExtractPort -address $localaddress
$remoteaddress, $remoteport = ExtractPort -address $remoteaddress
$process = Get-Process -Id $process
[pscustomobject]@{
state = $state
proto = $proto
localaddress = $localaddress
localport = $localport
remoteaddress = $remoteaddress
remoteport = $remoteport
Process = $process
} # PScustomobject
} # Foreach connection

I’ll try this post again.

#This deals with IPV6 addresses
function ExtractPort ($address) {
    if ($address -match "\[.*") { 
        $addr, $port = $address -split "\]:" 
        $addr + "]"
        $port
    } #if IPV6
    else {$address -split ":"}
}

foreach ($connection in (netstat -ano)) {
    #disregard header rows
    If ($connection -notlike "*TCP*" -and $connection -notlike "*UDP*") {continue}
    # Split the rows into fields and disregard headers
    switch -wildcard ($connection)
    {
        '*TCP*'  {$proto, $localaddress, $remoteaddress, $state, $process  = -split $connection}
        '*UDP*'  {$proto, $localaddress, $remoteaddress, $process = -split $connection; $state = "STATELESS"}
    } # switch
    $localaddress, $localport = ExtractPort -address $localaddress
    $remoteaddress, $remoteport = ExtractPort -address $remoteaddress
    $process = Get-Process -Id $process   
    [pscustomobject]@{
        state         = $state
        proto         = $proto
        localaddress  = $localaddress
        localport     = $localport
        remoteaddress = $remoteaddress
        remoteport    = $remoteport
        Process       = $process
    } # PScustomobject  
} # Foreach connection

Try this function Test-Port. I downloaded it and modified to correct UDP option which was not working. Give it a whirl.

    # inspired by https://gallery.technet.microsoft.com/scriptcenter/97119ed6-6fb2-446d-98d8-32d823867131

    Function Test-Port {
    <# .SYNOPSIS Tests a Port or a range of ports on a specific ComputerName(s). .DESCRIPTION Tests a Port or a range of ports on a specific ComputerName(s). Creates a custom object with the properties: ComputerName, Protocol, Port, Open, Notes. .PARAMETER ComputerName A single ComputerName or array of ComputerName to test the port connection on. .PARAMETER Port Port number to test ([int16] 0 - 65535), an array can also be passed .PARAMETER TCP Use TCP as the transport protocol .PARAMETER UDP Use UDP as the transport protocol .PARAMETER TimeOut Sets a timeout for TCP or UDP port query. (In milliseconds, Default is 1000) .NOTES Author: Bill Riedy Version: 1.0 Date: 2018/03/13 To Do: UDP port testing not currently working .EXAMPLE Test-Port -ComputerName 'server' -port 80 Checks port 80 on server 'server' to see if it is listening .EXAMPLE 'server' | Test-Port -Port 80 Checks port 80 on server 'server' to see if it is listening .EXAMPLE Test-Port -ComputerName @("server1","server2") -Port 80 Checks port 80 on server1 and server2 to see if it is listening .EXAMPLE @("server1","server2") | Test-Port -Port 80 Checks port 80 on server1 and server2 to see if it is listening .EXAMPLE (Get-Content hosts.txt) | Test-Port -Port 80 Checks port 80 on servers in host file to see if it is listening .EXAMPLE Test-Port -ComputerName (Get-Content hosts.txt) -Port 80 Checks port 80 on servers in host file to see if it is listening .EXAMPLE Test-Port -ComputerName (Get-Content hosts.txt) -Port @(1..59) Checks a range of ports from 1-59 on all servers in the hosts.txt file .OUTPUTS [psobject] An array of objects containing the fields: ComputerName A string containing the computer name or ip address that was passed to the function Protocol A string being either 'TCP' or 'UDP' Port An integer in the range 1 - 65535 Open A boolean Notes Any notes when attempting to make a connection .LINK about_Properties #>

        #region Parameter
        [cmdletbinding(
            DefaultParameterSetName = '',
            ConfirmImpact = 'low'
        )]
        [OutputType([psobject])]
        Param(
            [Parameter(
                Mandatory,
                HelpMessage = 'Enter a ComputerName or IP address',
                Position = 0,
                ValueFromPipeline)
            ]
            [string[]] $ComputerName,
            [Parameter(
                Position = 1,
                Mandatory,
                HelpMessage = 'Enter an integer port number (1-65535)')]
            [uint16[]] $Port,
            [int] $Timeout = 1000,
            [switch] $TCP,
            [switch] $UDP
        )
        #endregion Parameter
        Begin {
            Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"
            if (!$tcp -AND !$udp) {
                $tcp = $True
            }
            #Typically you never do this, but in this case I felt it was for the benefit of the function
            #as any errors will be noted in the output of the report
            $oldEA = $ErrorActionPreference
            $ErrorActionPreference = 'SilentlyContinue'
            Write-Verbose -Message "Saving current value of `$ErrorActionPreference [$($oldEa)] and setting it to 'Stop'"
            $report = @()
        }
        Process {
            foreach ($c in $ComputerName) {
                foreach ($p in $port) {
                    if ($tcp) {
                        #Create temporary holder
                        #$temp = '' | Select-Object -Property ComputerName, Protocol, Port, Open, Notes
                        $temp = New-Object -TypeName psobject -Property @{ Computername = ''; Protocol = ''; Port = 0; Open = $false; Notes = '' }
                        #Create object for connecting to port on computer
                        $tcpobject = New-Object -TypeName system.Net.Sockets.TcpClient
                        #Connect to remote machine's port
                        $connect = $tcpobject.BeginConnect($c, $p, $null, $null)
                        #Configure a timeout before quitting
                        $wait = $connect.AsyncWaitHandle.WaitOne($Timeout, $false)
                        #if timeout
                        if (!$wait) {
                            #Close connection
                            $tcpobject.Close()
                            Write-Verbose -Message 'Connection Timeout'
                            #Build report
                            $temp.ComputerName = $c
                            $temp.Port = $p
                            $temp.Protocol = 'TCP'
                            $temp.Open = $false
                            $temp.Notes = 'Connection to Port Timed Out'
                        } else {
                            $error.Clear()
                            $null = $tcpobject.EndConnect($connect)
                            #if error
                            if ($error[0]) {
                                #Begin making error more readable in report
                                [string] $string = ($error[0].exception).message
                                $message = (($string.split(':')[1]).replace('"', '')).TrimStart()
                                $failed = $true
                            }
                            #Close connection
                            $tcpobject.Close()
                            #if unable to query port to due failure
                            if ($failed) {
                                #Build report
                                $temp.ComputerName = $c
                                $temp.Port = $p
                                $temp.Protocol = 'TCP'
                                $temp.Open = $false
                                $temp.Notes = "$message"
                            } else {
                                #Build report
                                $temp.ComputerName = $c
                                $temp.Port = $p
                                $temp.Protocol = 'TCP'
                                $temp.Open = $true
                                $temp.Notes = "Successful link to $c $($temp.Protocol) port $p"
                            }
                        }
                        #Reset failed value
                        $failed = $Null
                        #Merge temp array with report
                        $report += $temp
                    }
                    if ($udp) {
                        #$temp = '' | Select-Object -Property ComputerName, Protocol, Port, Open, Notes
                        $temp = New-Object -TypeName psobject -Property @{ Computername = ''; Protocol = ''; Port = 0; Open = $false; Notes = '' }
                        Write-Verbose -Message 'Making UDP connection to remote server'
                        $Socket = New-Object -TypeName Net.Sockets.Socket -ArgumentList ( 'InterNetwork', 'Dgram', 'Udp' )
                        $Socket.SendTimeOut = $Timeout  # ms
                        $Socket.ReceiveTimeOut = $Timeout  # ms
                        try {
                            $Socket.Connect( $C, $p )
                            $Buffer = New-Object -TypeName byte[] -ArgumentList 48
                            $Buffer[0] = 27
                            Write-Verbose -Message 'Sending message to remote host'
                            $null = $Socket.Send(    $Buffer )
                            $null = $Socket.Receive( $Buffer )
                            $temp.ComputerName = $c
                            $temp.Port = $p
                            $temp.Protocol = 'UDP'
                            $temp.Open = $true
                            $temp.Notes = ''
                        } catch {
                            Write-Verbose -Message 'Communication failed'
                            Write-Error -Message $error[0]
                            $temp.ComputerName = $c
                            $temp.Port = $p
                            $temp.Protocol = 'UDP'
                            $temp.Open = $false
                            $temp.Notes = $error[0].exception
                        }
                        $socket.dispose()
                        Remove-Variable -Name socket
                        #Merge temp array with report
                        $report += $temp
                    }
                }
            }
        } End {
            #Generate Report
            Write-Output -InputObject $report
            Write-Verbose -Message "Resetting value of `$ErrorActionPreference back to [$($oldEa)]"
            Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
            $ErrorActionPreference = $oldEA
        }
    } #EndFunction Test-Port

Hi mates, thank you really a lot for your kind support!!
I’ve noticed also that Win7 doesn’t support also “New-NetFirewallRule” so I’ve tried to switch to the old DOS support…
I’ve found a good program called PortCheck.exe (if I can post the link here, and may be useful: http://www.portcheck-tool.com/) and I’ve found the way to wrote a simple script in old DOS school, here it is:

:start
@echo off
echo Test Camera 1
c:\portcheck 192.168.0.102 554
if %ERRORLEVEL%==1 (
echo Camera1 OK
netsh advfirewall firewall delete rule name=“Cam1-block”
) else (
echo Camera1 REBOOT
netsh advfirewall firewall add rule name=“Cam1-block” enable=yes dir=in action=block remoteip=192.168.0.102 protocol=ICMPv4 profile=any
)

timeout 20
cls
goto :start

Thank you all!!!