Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- Description:
- A function to test if a connection can be made to a specific TCP port
- Parameters:
- $hostname [String] - The hostname to connect to, ie. www.google.com
- $port [Int32] - The port to connect to
- Return Value:
- This function returns a custom PSObject of the following format:
- $object.Status = True/False (Whether or not the test passed)
- $object.Exception = The exception that occured if the test failed
- #>
- function Test-TcpPortConnection {
- param($hostname,$port)
- try {
- $tcp = New-Object System.Net.Sockets.TcpClient
- $tcp.Connect($hostname,$port)
- $tcp.Close()
- return New-Object PSObject -Property @{
- Pass=$true;
- Exception=$null;
- }
- }
- catch [System.ArgumentNullException] {
- return New-Object PSObject -Property @{
- Pass=$false;
- Exception="Null argument passed";
- }
- }
- catch [ArgumentOutOfRangeException] {
- return New-Object PSObject -Property @{
- Pass=$false;
- Exception="The port is not between MinPort and MaxPort";
- }
- }
- catch [System.Net.Sockets.SocketException] {
- return New-Object PSObject -Property @{
- Pass=$false;
- Exception="Socket exception";
- }
- }
- catch [System.ObjectDisposedException] {
- return New-Object PSObject -Property @{
- Pass=$false;
- Exception="TcpClient is closed";
- }
- }
- catch {
- return New-Object PSObject -Property @{
- Pass=$false;
- Exception="Unhandled Error";
- }
- }
- }
- # Returns True unless your network is messed up
- $result = Test-TcpPortConnection "www.google.com" 80
- if($result.Pass) {
- Write-Host "Test passed: www.google.com:80"
- }
- # Will fail unless your dns resolves this
- $result = Test-TcpPortConnection "www.thisisnotarealhost.com" 80
- if(!$result.Pass) {
- Write-Host "An exception occured:" $result.Exception
- }
- # Will fail because of invalid port range
- $result = Test-TcpPortConnection "www.google.com" 100000000
- if(!$result.Pass) {
- Write-Host "An exception occured:" $result.Exception
- }
- <# Sample Output:
- Test passed: www.google.com:80
- An exception occured: Socket exception
- An exception occured: The port is not between MinPort and MaxPort
- #>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement