Is it possible to simplify this PowerShell closure idea?

Viewed 31

In the following idea, I think the syntax | & $LogIt is a little messy. It is (IMO) certainly better than having tons of | Out-File -FilePath thelog.log -Append sprinkled in a script. I find that it is WAY too easy to cut-paste and forget to change the logfile name. Even worse is when forgetting to "initialize" (not -Append) a log once.

Am I missing another PowerShell concept that would help accomplish the idea behind this closure?

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

This sample doesn't show some other "features" in MakeLogFile to focus my question.

1 Answers

Assign the resulting closure to an item in the function: drive - this will have the same effect as if you had defined it using the function keyword, and you therefore no longer need to use an explicit call operator:

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
Related