Accepting null input

Commands such as Where-Object allow an explicit null value in the input pipeline. To allow null in an input pipeline, the [AllowNull()] attribute would be added to the InputObject parameter. There is a difference between supporting $null | Get-InputObject and implementing pipeline support originating from a command that returns nothing: AllowNull is only needed when an explicit null is in the input pipeline.

In the following example, the Get-EmptyOutput function has no body and will not return anything. This simulates a command that returns nothing because all of the output is filtered out. The Get-InputObject function can take part in a pipeline with Get-EmptyOutput without using AllowNull:

function Get-EmptyOutput { }
function Get-InputObject {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)]
$InputObject
)
}
# No output, no error
First | Second

If Get-EmptyOutput were to explicitly return null, which is not a good practice, Get-InputObject would raise a parameter binding error:

PS> function First { return $null }
PS> First | Second

Second : Cannot bind argument to parameter 'InputObject' because it is null.
At line:1 char:9
+ First | Second
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [Second], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Second

Adding AllowNull would sidestep this error, but Get-InputObject would have to handle a null value internally:

function Get-EmptyOutput { return $null }
function Get-InputObject {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)]
[AllowNull()]
$InputObject
)
if ($InputObject) {
# Do work
}
}
# No output, no error
First | Second

If this were real output from a function, it may be better to consider the output from Get-EmptyOutput to be a bug and pass it through Where-Object to sanitize the input, which avoids the need to add AllowNull, for example:

Get-EmptyOutput | Where-Object { $_ } | Get-InputObject
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.160.216