Scripts to support both command line and pipeline processing

Welcome Forums General PowerShell Q&A Scripts to support both command line and pipeline processing

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

  • Author
    Posts
  • #5625

    Member
    Topics: 1562
    Replies: 0
    Points: 0
    Rank: Member

    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.

The topic ‘Scripts to support both command line and pipeline processing’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort