需要格式化 powershell 中函数的输出

Need to format output from function in powershell

我有一个用 powershell 编写的脚本,它可以得到 0 到 N 之间的斐波那契数列。

代码:

$n = $args[0]
Function Get-Fib ($n) {
     $current = $previous = 1;
     while ($current -lt $n) {
           $current;
           $current,$previous = ($current + $previous),$current}
     }
Get-Fib $n

输入:&.\script2.ps17

预期输出:1 1 2 3 5

但是,现在输出如下所示:

1

2

3

5

是否可以在这个脚本中得到没有换行符的输出?

您可以像这样构建输出

Function Get-Fib ($n) {
    $output = ""
    $current = $previous = 1;
    while ($current -lt $n) {
        $output += "$current "
        $current,$previous = ($current + $previous),$current
    }
    $output
}

Get-Fib 100

1 2 3 5 8 13 21 34 55 89

或者您可以将整个代码段包含在子表达式 $(...) 中,然后像这样用 space 连接在一起。

Function Get-Fib ($n) {
    $current = $previous = 1;
    $(
    while ($current -lt $n) {
        $current
        $current,$previous = ($current + $previous),$current
    }
    ) -join " "
}

Get-Fib 100

1 2 3 5 8 13 21 34 55 89

不修改函数只修改调用方:

( Get-Fib 6 ) -join ' '

通过将函数调用括在括号中,我们得到的结果是一个数组,可以使用 -join 运算符连接。

这样函数就保持了它的灵活性。在 single responsibility principle 之后,该函数不应该关心格式化,它应该只做它的基本工作,即计算并以本机数据格式输出结果。

这使我们能够在更广泛的上下文中使用该函数,例如。 G。将其输出传递给需要序列的其他 cmdlet:

( Get-Fib 6 | Sort-Object -Descending ) -join ' '