by scottbass at 2013-03-04 19:15:49
Hi,by DonJ at 2013-03-06 03:52:37
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
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.