Twinfriends
Twinfriends

Reputation: 1987

How does this function return its value?

I'm actually scripting and a part of my script is a FTP file download. The code words without any problem, but I don't understand one specific part. Its the only part from the code I haven't written by myself. I understand how the code works, but I actually dont understand how the function return its value. You're may confused what I mean, so let me explain it with a bit of code:

function get-ftp {

    try {

        $ftprequest = [system.net.ftpwebrequest]::Create($uri)
        $ftprequest.Credentials = New-Object system.net.networkcredential($user,$pass)
        $ftprequest.Proxy = $null
        $ftprequest.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
        $ftpresponse = $ftprequest.GetResponse()
        $reader = New-Object IO.StreamReader $ftpresponse.GetResponseStream() 
        $reader.ReadToEnd()
        $reader.Close()
        $ftpresponse.Close()

    }

    catch {

        Write-host "Error while reading filenames"

    }
}

So this is my function to get all directories from the FTP server. I call this function with this code:

$allXmlFiles = get-ftp

So after the call, my $allXmlFiles contains a string (tested with getType on $allXmlFiles) with all the filenames on the server. Now my question: How is the answer from the FTP passed to this variable? There's no return in the function, so I'm quite confused how this works. I tried so take the try/catch out of the function and access the answer directly, but that didin't work. I tried to find it in $reader and in $ftpresponse - no success.

It would be really cool if someone can explain me whats going on here. As said, the code works, but I would like to understand whats going on here.

Upvotes: 1

Views: 64

Answers (2)

Martin Brandl
Martin Brandl

Reputation: 58931

In PowerShell, the result of every command / statement is returned as output if you don't assign or pipe it to anything. The return keyword only exits the current scope. You rarely use return in PowerShell.

As beatcracker mentioned, $reader.ReadToEnd() is producing the output.

Upvotes: 4

beatcracker
beatcracker

Reputation: 6920

It's

$reader.ReadToEnd()

StreamReader.ReadToEnd() method outputs string and since it's result is not assigned to variable it will be the function output.

Idiomatic way would be to write it like this:

Write-Output $reader.ReadToEnd()

Upvotes: 6

Related Questions