是否有可能简化这个 PowerShell 闭包的想法?

Is it possible to simplify this PowerShell closure idea?

下面的思路,我觉得语法| & $LogIt有点乱。它(IMO)肯定比在脚本中散布大量 | Out-File -FilePath thelog.log -Append 更好。我发现剪切粘贴并忘记更改日志文件名太容易了。更糟糕的是忘记“初始化”(不是-Append)一个日志 once.

我是否遗漏了另一个有助于实现此闭包背后的想法的 PowerShell 概念?

function MakeLogFile([string]$filename)
{
    Get-Date | Out-File -FilePath $filename

    {
        param(
            [ Parameter(ValueFromPipeline=$true,Mandatory=$true) ]
            [string] $in
         )
        process {
            $in | Out-File -FilePath $filename -Append
        }
    }.GetNewClosure()

}

$LogIt = MakeLogFile thelog.log

&$LogIt "monkey"

"1" | & $LogIt
"2" | & $LogIt

此示例未显示 MakeLogFile 中的一些其他“功能”来关注我的问题。

将生成的闭包分配给 function: 驱动器中的项目 - 这与使用 function 关键字定义它的效果相同,因此您不再需要使用显式调用运算符:

function New-LogFile
{
  param([string]$filename)

  Get-Date | Out-File -FilePath $filename
  {
      param(
          [ Parameter(ValueFromPipeline=$true,Mandatory=$true) ]
          [string] $in
      )
      process {
          $in | Out-File -FilePath $filename -Append
      }
  }.GetNewClosure()
}

# Assign closure to function: drive item
${function:Out-Log} = New-LogFile path\to\file.log

# Now we can call it like any other function
1..5 |Out-Log