Mark Minasi's Tech Forum
Register Calendar Latest Topics Chat
 
 
 


Reply
  Author   Comment  
jsclmedave

Administrator
Registered:
Posts: 418
Reply with quote  #1 
Tim,

"When working  Dot Net Assembly [System.Net.Sockets.TcpClient] The Dispose Method is not working in Option 1.  So I Updated my script to use Option 2.  I was wondering what could I be doing different to close the connection for Option 1 so I don’t need to track a connection object in Option 2?   Option 1 is causing Buffer Overflows"

NOTE!!  I removed the Help Content due to character limitations while posting. Full code is available upon request..

Examples:

#Option 1 Dispose connection does not work

$Device = '10.10.10.117'

$ResultsObject01 = (New-Object -TypeName System.Net.Sockets.TCPClient).ConnectAsync($Device,135)

 
#Dispose Connection (NOT Working)

$ResultsObject01

$ResultsObject01.Dispose()

 

#Option 2 Dispose Connection Object Works

$Device = '10.10.10.93'

$ConnObject = New-Object -Type pscustomobject

$ConnObject | Add-Member -MemberType NoteProperty -Name 'IPAddress' -Value $Device

$ConnObject | Add-Member -MemberType NoteProperty -Name 'DCOM' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)

 

$ResultsObject02 = New-Object -Type pscustomobject

$ResultsObject02 | Add-Member -MemberType NoteProperty -Name 'IPAddress' -Value $Device

$ResultsObject02 | Add-Member -MemberType NoteProperty -Name 'DCOM' -Value ($ConnObject[0].DCOM.ConnectAsync($Device,135))

 #Dispose Connection  (Working)

$ResultsObject02.DCOM

$ConnObject.DCOM.Dispose()

 

Example: Return Results and Object Method List

#Option 1 Dispose connection doesn’t not work

Code:

$ResultsObject01

 Result                 : System.Threading.Tasks.VoidTaskResult

Id                     : 65229

Exception              :

Status                 : RanToCompletion

IsCanceled             : False

IsCompleted            : True

CreationOptions        : None

AsyncState             :

IsFaulted              : False

AsyncWaitHandle        :

CompletedSynchronously : False

 

 

$ResultsObject01 | Get-Member -MemberType Method

     TypeName: System.Threading.Tasks.Task`1[[System.Threading.Tasks.VoidTaskResult, mscorlib, Version=4.0.0.0,

Culture=neutral, PublicKeyToken=b77a5c561934e089]]

 

Name             MemberType Definition                                                                            

----             ---------- ----------                                                                            

ConfigureAwait   Method     System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1[[System.Threading.Tasks.Vo...

ContinueWith     Method     System.Threading.Tasks.Task ContinueWith(System.Action`1[[System.Threading.Tasks.Tas...

Dispose          Method     void Dispose(), void IDisposable.Dispose()                                            

Equals           Method     bool Equals(System.Object obj)                                                        

GetAwaiter       Method     System.Runtime.CompilerServices.TaskAwaiter`1[[System.Threading.Tasks.VoidTaskResult...

GetHashCode      Method     int GetHashCode()                                                                     

GetType          Method     type GetType()                                                                        

RunSynchronously Method     void RunSynchronously(), void RunSynchronously(System.Threading.Tasks.TaskScheduler ...

Start            Method     void Start(), void Start(System.Threading.Tasks.TaskScheduler scheduler)              

ToString         Method     string ToString()                                                                     

Wait             Method     void Wait(), bool Wait(timespan timeout), void Wait(System.Threading.CancellationTok...

 

 

 

#Dispose Connection  (Working)

 

Code:

$ResultsObject02.DCOM

 

 

Result                 : System.Threading.Tasks.VoidTaskResult

Id                     : 65230

Exception              :

Status                 : RanToCompletion

IsCanceled             : False

IsCompleted            : True

CreationOptions        : None

AsyncState             :

IsFaulted              : False

AsyncWaitHandle        : System.Threading.ManualResetEvent

CompletedSynchronously : False

 

 

 

$ConnObject.DCOM | Get-Member -MemberType Method

 

 

   TypeName: System.Net.Sockets.TcpClient

 

Name         MemberType Definition                                                                                

----         ---------- ----------                                                                                

BeginConnect Method     System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCall...

Close        Method     void Close()                                                                              

Connect      Method     void Connect(string hostname, int port), void Connect(ipaddress address, int port), void...

ConnectAsync Method     System.Threading.Tasks.Task ConnectAsync(ipaddress address, int port), System.Threading....

Dispose      Method     void Dispose(), void IDisposable.Dispose()                                                 

EndConnect   Method     void EndConnect(System.IAsyncResult asyncResult)                                          

Equals       Method     bool Equals(System.Object obj)                                                            

GetHashCode  Method     int GetHashCode()                                                                         

GetStream    Method     System.Net.Sockets.NetworkStream GetStream()                                              

GetType      Method     type GetType()                                                                            

ToString     Method     string ToString()                                                                         

 

 

 

 



Code:

Function Get-MiniDiscovery
<#

.NOTES

Refrence Asynchronous Infomation
# Author: Boe Prox
# https://github.com/proxb/AsyncFunctions

Name: Get-MiniDiscovery
Author: Preston Padgett
Version History:
1.1 //Preston Padgett - 3/20/2017

#>


{

    [CmdletBinding(SupportsShouldProcess=$true, 
                  PositionalBinding=$false,
                  HelpUri = 'https://path/name/MiniDiscovery',
                  ConfirmImpact='Medium')]
    [Alias('GMD')]
    [OutputType([System.Object])]
Param
(
    # Param1 List of Valid IP Address
    [Parameter(Mandatory=$false, 
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true,
                    Position=0)]
    [ValidateNotNull()]
    [ValidateNotNullOrEmpty()]
    [Alias('IP')]
    [ValidateScript({$_ -match [IPAddress[]]$_ })] 
    $IPAddress,
    # Param3 TCP Connection Max Time Out
    [Parameter(Mandatory=$false,
                Position=1)]
    [Alias('MT')]
    [int32]$TCPTimeout = 300,
    # Param4 TCP Connection Max Time Out
    [Parameter(Mandatory=$false,
                Position=2)]
    [Alias('ML')]
    [ValidateScript({$_ -le 2000})]
    [int32]$MaxLimit = 2000,
       
    # Param4 Location for Log file
    [Parameter(Mandatory=$false, 
        Position=3)]
    [AllowNull()]
    [AllowEmptyCollection()]
    [AllowEmptyString()]
    [Alias('LOG')]
    [ValidateScript({if ($_){Test-Path ([io.path]::GetDirectoryName("$_")) -PathType ‘Container’}else{Continue}})] 
    [string]$ErrorLogPath
)

    Begin
    {
    $Result = @()
    $ConnObjectList = @()
    $i = 0
    $c = 0
    $ComputerArraylist = New-Object -TypeName System.Collections.ArrayList
    foreach ($IP in $IPAddress) {
        [void]$ComputerArraylist.Add($IP)
    }
    }
    Process
    {
        
        Do {
            Write-Progress -Activity "Gathering Asynchronous Connection for Mini Discovery $C" -Status "Disposing up to $MaxLimit Connection Aynchronously" -PercentComplete ($C/$ComputerArraylist.Count*100)
            $TempRunList = foreach ($Device in ($ComputerArraylist[$i..(($i+= $MaxLimit) -1 )])) {
                    
                    $ConnObject = $null
                    $ConnObject = New-Object -Type pscustomobject
                  $ConnObject | Add-Member -MemberType NoteProperty -Name 'IPAddress' -Value $Device
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'DCOM' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'WINS' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'RDP' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'HTTPWinRM' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'HTTPSWinRM' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'FTP' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'SSH' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                    $ConnObject | Add-Member -MemberType NoteProperty -Name 'TelNet' -Value (New-Object -TypeName System.Net.Sockets.TCPClient)
                   
                    $ConnObjectList += $ConnObject
                    [pscustomobject]@{
                    IPAddress = $Device                    
                    FQDN = [System.Net.Dns]::GetHostEntryAsync($Device)
                    ICMP = (New-Object System.Net.NetworkInformation.Ping).SendPingAsync($Device,$TCPTimeout)
                    DCOM = $ConnObjectList[$c].DCOM.ConnectAsync($Device,135)
                    WINS = $ConnObjectList[$c].WINS.ConnectAsync($Device,139)
                    RDP = $ConnObjectList[$c].RDP.ConnectAsync($Device,3389)
                    HTTPWinRM = $ConnObjectList[$c].HTTPWinRM.ConnectAsync($Device,5985)
                    HTTPSWinRM = $ConnObjectList[$c].HTTPSWinRM.ConnectAsync($Device,5986)
                    FTP = $ConnObjectList[$c].FTP.ConnectAsync($Device,21)
                    SSH = $ConnObjectList[$c].SSH.ConnectAsync($Device,22)
                    TelNet = $ConnObjectList[$c].TelNet.ConnectAsync($Device,23)
                    }

                $c++
                Write-Progress -Activity "Gathering Asynchronous Connection for Mini Discovery $C" -Status "Disposing up to $MaxLimit Aynchronous Connection" -PercentComplete ($C/$ComputerArraylist.Count*100)               
            }
     
            # While Function is used for an active pause
            while (($TempRunList.ICMP.GetAwaiter().IsCompleted) -ccontains $false){}
            $TempRunList.ICMP.Dispose()
            while (($TempRunList.FQDN.GetAwaiter().IsCompleted) -ccontains $false){}
            $TempRunList.FQDN.Dispose()
            while (($TempRunList.DCOM.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.DCOM.Dispose()
            $ConnObjectList.DCOM.Close()
            while (($TempRunList.WINS.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.WINS.Dispose()
            $ConnObjectList.WINS.Close()
            while (($TempRunList.RDP.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.RDP.Dispose()
            $ConnObjectList.RDP.Close()
            while (($TempRunList.HTTPWinRM.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.HTTPWinRM.Dispose()
            $ConnObjectList.HTTPWinRM.Close()
            while (($TempRunList.HTTPSWinRM.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.HTTPSWinRM.Dispose()
            $ConnObjectList.HTTPSWinRM.Close()
            while (($TempRunList.FTP.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.FTP.Dispose()
            $ConnObjectList.FTP.Close()
            while (($TempRunList.SSH.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.SSH.Dispose()
            $ConnObjectList.SSH.Close()
            while (($TempRunList.TelNet.GetAwaiter().IsCompleted) -ccontains $false){}
            $ConnObjectList.TelNet.Dispose()
            $ConnObjectList.TelNet.Close()           
            
            $TempRunList | ForEach-Object {
                $IPv4 = $_.IPAddress
                $Result = $null
                $Result += @{IPv4 = $_.IPAddress}
                If ($_.ICMP) {
                    If ($_.ICMP.IsFaulted) {
                        $ICMP = $_.ICMP.Status
                        $Result += @{ICMPResult = $_.ICMP.Exception.GetBaseException().Message}
                    }
                    Else {
                        $ICMP = $_.ICMP.Result.Status
                    }
                }
                If ($_.FQDN) {
                    If ($_.FQDN.IsFaulted) {
                        $FQDN = $_.FQDN.Status
                        $Result += @{FQDNResult = $_.FQDN.Exception.GetBaseException().Message}
                    }
                    Else {
                        $FQDN = $_.FQDN.Result.HostName
                    }
                }
                If ($_.DCOM) {
                    If ($_.DCOM.IsFaulted) {
                        $DCOM = $_.DCOM.Status
                        $Result += @{DCOMResult = $_.DCOM.Exception.GetBaseException().Message}
                    }
                    Else {
                        $DCOM = $_.DCOM.Status
                    }
                }
                If ($_.WINS) {
                    If ($_.WINS.IsFaulted) {
                        $WINS = $_.WINS.Status
                        $Result += @{WINSResult = $_.WINS.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $WINS = $_.WINS.Status              
                    }          
                }
                If ($_.RDP) {
                    If ($_.RDP.IsFaulted) {
                        $RDP = $_.RDP.Status
                        $Result += @{RDPResult = $_.RDP.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $RDP = $_.RDP.Status              
                    }          
                }
                If ($_.HTTPWinRM) {
                    If ($_.HTTPWinRM.IsFaulted) {
                        $HTTPWinRM = $_.HTTPWinRM.Status
                        $Result += @{HTTPWinRMResult = $_.HTTPWinRM.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $HTTPWinRM = $_.HTTPWinRM.Status      
                    } 
                }
                If ($_.HTTPSWinRM) {
                    If ($_.HTTPSWinRM.IsFaulted) {
                        $HTTPSWinRM = $_.HTTPSWinRM.Status
                        $Result += @{HTTPSWinRMResult = $_.HTTPSWinRM.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $HTTPSWinRM = $_.HTTPSWinRM.Status
                    }
                }
                If ($_.FTP) {
                    If ($_.FTP.IsFaulted) {
                        $FTP = $_.FTP.Status
                        $Result += @{FTPResult = $_.FTP.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $FTP = $_.FTP.Status
                    }
                }
                If ($_.SSH) {
                    If ($_.SSH.IsFaulted) {
                        $SSH = $_.SSH.Status
                        $Result += @{SSHResult = $_.SSH.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $SSH = $_.SSH.Status
                    }
                }
                If ($_.TelNet) {
                    If ($_.TelNet.IsFaulted) {
                        $TelNet = $_.TelNet.Status
                        $Result += @{TelNetResult = $_.TelNet.Exception.GetBaseException().Message}
                    } 
                    Else {
                        $TelNet = $_.TelNet.Status
                    }
                }
                
                $ResultsObject = [pscustomobject]@{
                            IPv4 = $IPv4
                            FQDN = $FQDN
                            ICMP = $ICMP
                            DCOM = $DCOM
                            WINS = $WINS
                            RDP = $RDP
                            HTTPWinRM = $HTTPWinRM
                            HTTPSWinRM = $HTTPSWinRM
                            FTP = $FTP
                            SSH = $SSH
                            TelNet = $TelNet
                            Issues = $Result
                        }
     
                If ($ErrorLogPath) {
                    $ResultsObject | Select-Object IPv4, FQDN, ICMP, DCOM, WINS, RDP, HTTPWinRM, HTTPSWinRM, FTP, SSH, TelNet
                    $ResultsObject.Issues| Format-List * | Out-File $ErrorLogPath -Append
                }
                else{
                    $ResultsObject
                }                
            }
        }
        until ($i -ge $ComputerArraylist.Count -1 )    
       
    }
    End
    {
        
    }
}
if ($ErrorLogPath) {
    Get-MiniDiscovery -IPAddress $IPAddress -TCPTimeout $TCPTimeout -MaxLimit $MaxLimit -ErrorLogPath $ErrorLogPath
}
Else{
    Get-MiniDiscovery -IPAddress $IPAddress -TCPTimeout $TCPTimeout -MaxLimit $MaxLimit
}

__________________
Tim Bolton @jsclmedave
Email: [string](0..20|%{[char][int](32+('527377347976847978324785847679797514357977').substring(($_*2),2))}) -replace ' '  

New to the forum? Please Read this
0
Previous Topic | Next Topic
Print
Reply

Quick Navigation: