Scripts to support both command line and pipeline processing

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 11 months ago.

  • Author
    Posts
  • #5625

    by scottbass at 2013-03-04 19:15:49

    Hi,

    I want certain scripts to support both command line and pipeline processing. Here is a test script:

    [CmdletBinding()]
    param (
    [Alias("Fullname")]
    [Parameter(
    Mandatory=$true,
    ValueFromPipeline=$true,
    ValueFromPipelineByPropertyName=$true
    )]
    [String[]]$Path
    )

    begin{
    $ErrorActionPreference="Stop"
    $files=@()
    }
    process{
    $files += $_
    }
    end{
    if (-not $files) {
    $files = (Get-ChildItem $Path)
    }
    return $files
    }

    I don't really like testing for $files not empty as my logic condition. It seems a bit "indirect". But, I couldn't come up with a better approach for knowing whether there was pipeline input or not. Is there a better way to handle this?

    Thanks,
    Scott

    by DonJ at 2013-03-06 03:52:37

    You don't need to use $_.

    If called from the pipeline, $Path will contain one item at a time. If fed directly on the parameter, it'll contain a collection. So, either way, inside your PROCESS block you use a ForEach to enumerate $Path. It will ALWAYS contain SOMETHING because you've marked it as mandatory. Check out my Toolmaking book if you like – there are a slew of examples of doing this. The code's on MoreLunches.com.

You must be logged in to reply to this topic.