【问题标题】:Need to format output from function in powershell需要在powershell中格式化函数的输出
【发布时间】:2021-01-19 18:25:10
【问题描述】:

我有用 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.ps1 7

预期输出:1 1 2 3 5

但是,现在输出看起来像这样:

1

2

3

5

是否可以在此脚本中不使用换行符获得输出?

【问题讨论】:

    标签: powershell formatting output


    【解决方案1】:

    你可以像这样构建输出

    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
    

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

    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
    

    【讨论】:

    • 在第一个选项中,我认为我们应该在这里稍微改变一下, $output += " " + $current 。第二个选项太棒了。
    【解决方案2】:

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

    ( Get-Fib 6 ) -join ' '
    

    通过将函数调用括在括号中,我们将结果作为一个数组,可以使用-join 运算符进行连接。

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

    这使我们可以在更多种类的上下文中使用该函数,例如。 G。将其输出传递给其他需要序列的 cmdlet:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      相关资源
      最近更新 更多