views:

49

answers:

1

I have a function:

function QuerySMTPServer ([string]$strSMTPServerName) {
    # open up a socket to the SMTP server
    $socket = New-Object System.Net.Sockets.TCPClient
    $socket.connect($strSMTPServerName, 25)
    $socket # output for testing

    # read response data (should be a line starting with 220; cf. RFC821)
    $stream = $socket.getStream()
    $stream # output for testing
    ...

If I run the function and pass it our (well-configured and running) SMTP server address, the $socket and $stream objects that are outputted tell me I have 0 bytes available on the socket, and No data available on the stream:

PS C:\Users\dan.maftei\Documents> QuerySMTPServer "internal-smtp.XYZ.com"

($socket)
Client              : System.Net.Sockets.Socket
Available           : 0
Connected           : True
...
($stream)
DataAvailable : False

However, there IS indeed data available, since I can create a byte array and read into it with the read() method off the $stream object. In fact this is precisely what I do in the remainder of the function, and it all works without error. (!)

Weirder yet, if I manually input into the PowerShell executable the exact same cmdlets my function calls, my $socket suddenly (and rightly) claims it has 79 bytes of data, and my $stream likewise says it has available data:

PS C:\Users\dan.maftei\Documents> $socket = New-Object System.Net.Sockets.TCPClient

PS C:\Users\dan.maftei\Documents> $socket.connect("internal-smtp.XYZ.com", 25)

PS C:\Users\dan.maftei\Documents> $socket

Client              : System.Net.Sockets.Socket
Available           : 79
Connected           : True

PS C:\Users\dan.maftei\Documents> $stream = $socket.getStream()

PS C:\Users\dan.maftei\Documents> $stream

...
DataAvailable : True
...

What is going on?? Why do I get different objects if I run those very few cmdlets via the CLI as opposed to via the function? Why can I still read data off my $stream even though apparently it has none according to the output in the function?

+1  A: 

cf: http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/d6420c96-3cdc-4af8-86d3-224b61a3b52f

2nd post, by jrich: PS is hasty in scripts, it doesn't wait for remote data; making the script sleep for a second (which is probably overkill) fixes everything.

Dan M.