1

I've a simple function:

    function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            $messages
        )

        process {
            Write-Host $_ 
        }
    }

Based on ValueFromPipeline in can use the function with pipeline input, e.g.

 "a","b", "c" | Write-Log
 a
 b
 c

That's ok. But if I want to use my function in that way:

 Write-Log -message "a", "b", "c"

the automatic $_ variable is empty, and nothing is printed.

I also found these two stackoverflow links:

Both of them suggest the following pattern:

  function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            $messages
        )

        process {
            foreach ($message in $messages){
                Write-Host $message
            }
        }
    }

Above pattern works for my use case. But from my point of view is feels weird to call foreach in the `process´ block, since (as far as I've understood) the process block is called for every pipeline item. As there a better cleaner way to write functions supporting both use cases?

Thx.

Moerwald
  • 10,448
  • 9
  • 43
  • 83

1 Answers1

2

That's the way you have to do it if you want to pass an array to a parameter like

Write-Log -Messages a,b,c  

Otherwise you can only do

Write-Log -Messages a

You can still pipe an array in without the foreach:

Echo a b c | Write-Log

I appreciate cmdlets that can do both, like get-process.

js2010
  • 23,033
  • 6
  • 64
  • 66