DWRoelands
DWRoelands

Reputation: 4940

Appending a function return value to a string variable in Powershell

Assuming the following Powershell script...

function Process-Folder {
    [cmdletbinding()]
    param ([string]$Path)
    Process {
        $returnvalue = ""
        # code here that reads all of the .txt files in $path
        # and concatenates their contents to $returnvalue
    return $returnvalue
    }
}

I'd like to add lines to this script which call this function a couple of times to process several folders. I would write that code as follows:

$allFileContent = ""
$firstFolder = Process-Folder -Path "c:\foo"
$allFileContent = $allFileContent + $firstFolder

$secondFolder = Process-Folder -Path "c:\bar"
$allFileContent = $allFileContent + $secondFolder

This code works but seems inelegant and doesn't seem like "the Powershell way". I tried:

$filecontent = ""
$filecontent = $filecontent + Process-Folder -Path "C:\foo"
$filecontent = $filecontent + Process-Folder -Path "C:\bar"

But ISE gave me "unexpected token 'Process-Folder' in expression or statement. I also tried:

$filecontent = ""
$filecontent | Process-Folder -Path "C:\foo"
$filecontent | Process-Folder -Path "C:\bar"

Which returned...

The input object cannot be bound to any parameters for the command either because the 
command does not take pipeline input or the input and its properties do not match any 
of the parameters that take pipeline input.

How can I accomplish what the first snippet does in a more elegant/"Powershell-like" way?

Upvotes: 1

Views: 1339

Answers (1)

Matthew
Matthew

Reputation: 1166

Looks like you need to put parens around your commands to get them to execute first. Also don't forget that $x += 'a' is the same as $x = $x + 'a', and you can assign the first value, and add the second without having to assign the empty string first, so try this:

$filecontent = Process-Folder -Path "C:\foo"
$filecontent += Process-Folder -Path "C:\bar"

EDIT: I realized after I got done rewriting the code, that I had put it in a form where you no longer need the parens, so I removed them. But doing that completely lost the example I was using to show you how to fix the lines that were a problem for you before (duh).

So...the parens are needed when combining some data with the result of a function. You have to force the function to run first. So in your original format, you would need parens like so:

$filecontent = ""
$filecontent = $filecontent + (Process-Folder -Path "C:\foo")
$filecontent + $filecontent + (Process-Folder -Path "C:\bar")

You can read all about it in this article

For the pipe, you need to set up a variable in your function which can accept input from the pipeline. I think this article does a really good job of explaining how to use the pipeline if you decide to take that route.

Hope this helps!

Upvotes: 2

Related Questions