Moerwald
Moerwald

Reputation: 11304

Function pipeline support, can't bind argument to parameter

I created following simple funcion, where the parameter supports input from pipeline:

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

        process {
            Write-Host $_
        }
    }

If I call the function via e.g. :

    "test1", "test2" | Write-Log

It works as expected, but if I'm forwarding an empty string down the pipeline I get the folowing error:

C:\> "test1", "", "test2" | Write-Log
test1
Write-Log : Cannot bind argument to parameter 'PipeLineLoglines' because it is an empty string.
At line:1 char:24
+ "test1", "", "test2" | Write-Log
+                        ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:String) [Write-Log], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Write-Log

test2

I'm using PowerShell.Core:

C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.2.0
PSEdition                      Core
GitCommitId                    6.2.0
OS                             Microsoft Windows 10.0.17763
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Can someone explain why an empty string causes this error?

Thx

Upvotes: 2

Views: 322

Answers (1)

briantist
briantist

Reputation: 47872

It's because the parameter is Mandatory, and it's considered that an empty string did not satisfy that condition. Given that there are specific validation attributes to test for that, I don't like this behavior, but that's the way it is.

There is an attribute that can help you though, [AllowEmptyString()]:

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

        process {
            Write-Host $_
        }
    }

Upvotes: 3

Related Questions