function - 从写入 STDOUT 的函数返回值的最佳方法

标签 function powershell powershell-2.0

我有一些辅助函数可以写入 STDOUT 以进行记录。其中一些函数会向调用者返回一个值,但会返回函数的整个输出。

如何让我的函数写入 STDOUT 并将值返回给调用者,而返回值不会被函数调用期间发出的所有 STDOUT 污染?

我正在寻找某种设计模式或最佳实践。

考虑这个脚本:

Function a
{
    Write-Output "In Function a"
    $a = 4
    return $a   
}

$b = a

Write-Output "Outside function: `$b is $b"

输出是
Outside function: $b is In Function a 4
但我希望输出是:
In Function a
$b is 4

最佳答案

在 PowerShell 中,返回函数内所有未捕获的输出,而不仅仅是 return 的参数。 .来自 documentation :

In PowerShell, the results of each statement are returned as output, even without a statement that contains the return keyword.



函数看起来像这样并不重要:
function Foo {
  'foo'
}

或者像这样:
function Foo {
  'foo'
  return
}

或者像这样:
function Foo {
  return 'foo'
}

它将返回字符串 foo无论哪种方式。

为防止返回输出,您可以
  • 写入主机或其中之一 ouptput streams (取决于您要创建的输出类型):
    Function a {
      Write-Host 'some text'
      Write-Verbose 'verbose message'
      Write-Information 'info message'   # requires PowerShell v5 or newer
      $a = 4
      return $a
    }
    

    旁注:Write-Informationinformation stream 时,在 PowerShell v5 之前不可用被引入,并从该版本开始 Write-Host也写入该流而不是直接写入主机控制台。
  • 捕获变量中的输出或将其“分配”给 $null :
    Function a {
      $var = Write-Output 'some text'
      $null = Write-Output 'some text'
      $a = 4
      return $a
    }
    
  • 或将输出重定向到 $null :
    Function a {
      Write-Output 'some text' | Out-Null
      Write-Output 'some text' >$null
      $a = 4
      return $a
    }
    
  • 关于function - 从写入 STDOUT 的函数返回值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21232024/

    相关文章:

    powershell - Powershell 2 中的结构或对象

    linux - 函数内的函数未返回预期值

    scala - 在 Scala 中编写阶乘尾递归函数

    javascript - 方法 .includes() 不是函数错误

    windows - 如何比较本地文件与 FTP 服务器上文件的年龄,如果远程副本在 PowerShell 中较新则如何下载

    powershell - 在数组中查找字符串 Powershell V2.0

    python - [Python]比较两个zip文件的功能,一个位于FTP目录,另一个在我的本地机器上

    powershell - Invoke-Pester 只运行一个 Assert/It block

    powershell - 保留专有名称的DC部分

    json - 在Powershell 2.0中读取JSON对象