将函数 return 值附加到 Powershell 中的字符串变量

Appending a function return value to a string variable in Powershell

假设以下 Powershell 脚本...

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
    }
}

我想在这个脚本中添加几行,它调用这个函数几次来处理多个文件夹。我会这样写代码:

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

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

此代码有效,但看起来不够优雅,而且不像 "the Powershell way"。我试过了:

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

但 ISE 在表达式或语句中给了我“意外的标记 'Process-Folder'。我也试过:

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

哪个返回...

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.

如何以更优雅/"Powershell-like" 的方式完成第一个代码片段的功能?

看来您需要用括号括起您的命令才能让它们先执行。也不要忘记 $x += 'a'$x = $x + 'a' 相同,您可以分配第一个值,然后添加第二个值,而不必先分配空字符串,所以试试这个:

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

编辑:我在重写代码后意识到,我已经把它放在一个不再需要括号的表单中,所以我删除了它们。但是这样做完全失去了我用来向您展示如何修复之前对您来说有问题的行的示例(duh)。

所以...将某些数据与函数的结果组合时需要括号。您必须先将函数强制为 运行。所以在你的原始格式中,你需要这样的括号:

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

您可以阅读所有相关内容in this article

对于管道,您需要在函数中设置一个变量,该变量可以接受来自管道的输入。我认为 this article 在解释如何使用管道方面做得非常好,如果您决定采用那条路线的话。

希望对您有所帮助!