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.

1
  • 1
    The way you say 'feels weird' is actually the way that Microsoft examples do it. Commented May 31, 2019 at 15:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.