【问题标题】:Appending a function return value to a string variable in Powershell将函数返回值附加到 Powershell 中的字符串变量
【发布时间】:2020-02-14 20:51:23
【问题描述】:

假设以下 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

此代码有效,但看起来不优雅,看起来不像“Powershell 方式”。我试过了:

$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”的方式完成第一个 sn-p 的工作?

【问题讨论】:

    标签: powershell string-concatenation


    【解决方案1】:

    看起来您需要在命令周围加上括号才能让它们首先执行。另外别忘了$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 很好地解释了如果您决定采用这条路线,如何使用管道。

    希望这会有所帮助!

    【讨论】:

    • 这正是我希望得到的有见地的答案。你是SO的功劳。谢谢!
    • 当问题布置得这么好时,很容易给出深思熟虑的答案。很高兴这对您有所帮助!
    猜你喜欢
    • 2017-01-09
    • 1970-01-01
    • 2016-03-28
    • 2016-07-14
    • 2011-11-14
    • 1970-01-01
    • 2021-03-23
    • 2014-02-17
    • 2012-09-09
    相关资源
    最近更新 更多