search
Categories
Sponsors
VirtualMetric Hyper-V Monitoring, Hyper-V Reporting
Archive
Blogroll

Badges
MCSE
Community

Cozumpark Bilisim Portali
Posted in Windows Powershell, Windows Server | No Comment | 1,514 views | 19/02/2014 17:44

This is a simple Telnet Function for switch management purposes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Telnet Function
Function Get-Telnet
{   param (
        [Parameter(ValueFromPipeline=$true)]
        [String[]]$Commands,
        [string]$RemoteHost,
        [string]$Port = "23",
        [int]$WaitTime = 1000
    )
 
	# Attach to the remote device, setup streaming requirements
    $Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
    if ($Socket)
    {   $Stream = $Socket.GetStream()
        $Writer = New-Object System.IO.StreamWriter($Stream)
        $Buffer = New-Object System.Byte[] 1024 
        $Encoding = New-Object System.Text.AsciiEncoding
 
        # Now start issuing the commands
        foreach ($Command in $Commands)
        {   $Writer.WriteLine($Command) 
            $Writer.Flush()
            Start-Sleep -Milliseconds $WaitTime
        }
 
		# All commands issued, but since the last command is usually going to be
        # the longest let's wait a little longer for it to finish
        Start-Sleep -Milliseconds ($WaitTime * 4)
        $Result = ""
 
		# Save all the results
        while($Stream.DataAvailable) 
        {   $Read = $Stream.Read($Buffer, 0, 1024) 
            $Result += ($Encoding.GetString($Buffer, 0, $Read))
        }
    }
    else     
    {   $Result = "Unable to connect to host: $($RemoteHost):$Port"
    }
 
	# Done
    $Result
}

I got the source code from this web page:

Modified a few parts to use in my environment.