Skip to content

Handle Piped $null In Collection In process{} #659

@mattcargile

Description

@mattcargile

Hello again,

Just had another thought. A $null is foreach-ed away normally. I was thinking it might be nice to alert the user they have $null values in their piped in data. So what do you think about the below approach? Is it how you imagined such a scenario?

Code

function Invoke-HandlePipedNullValue {
    [CmdletBinding()]
    param (
        # Parameter array accepting nulls, empty strings, and whitespace
        [Parameter(Mandatory, ValueFromPipeline)]
        [AllowEmptyString()]
        [AllowNull()]
        [string[]]
        $Value
    )
    begin{
        $canInterrupt = $true
    }
    
    process {
        if ((Test-PSFFunctionInterrupt) -and $canInterrupt) {
            return
        }
        if ($null -eq $Value) {
            $canInterrupt = $false
            Stop-PSFFunction -Message 'I am null but don''t kill the next process block' -Level Error
            return
        }
        foreach ($currentItemName in $Value) {
            "hello i am the current item: $currentItemName"
        }
    }
    
    end {
        # Curious how to handle interruptions here. I can't think of a scenario where I would want to interrupt the below if one item failed in the process block
    }
}
Usage
@($null,'','234325') | Invoke-HandlePipedNullValue

For end{}, my assumption is one would just reset the process{} layer interrupt variable if you had a scenario where an error in the process{} required interruption of the end{}.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions