0

Take for example the optional parameter -Filter on Get-ChildItem.

If one were to incorporate a call to Get-ChildItem in a PowerShell script, how can -Filter be exposed also as an optional parameter on the script such that it will only be passed to the cmdlet if specified?

2 Answers 2

1

You could use the $PSBoundParameters automatic variable to splat the relevant parameters of your script to Get-ChildItem:

[CmdletBinding()]
param(
  [Parameter(Mandatory)]
  [string]$Path,
  [Parameter()]
  [psobject]$NonGetChildItemParam
  [Parameter()]
  [string]$Filter
)

if($PSBoundParameters.ContainsKey("NonGetChildItemParam"))
{
    $PSBoundParameters.Remove("NonGetChildItemParam")
}

Get-ChildItem @PSBoundParameters
Sign up to request clarification or add additional context in comments.

Comments

0

You need to give the script an optional parameter -Filter and pass its argument through to Get-ChildItem.

Param(
  [Parameter(Mandatory=$true)]
  [string]$Path,
  [Parameter(Mandatory=$false)]
  [scriptblock]$Filter
)

if ($Filter) {
  Get-ChildItem $Path -Filter $Filter
} else {
  Get-ChildItem $Path
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.