I am looking to create a function that could toggle the ability to recurse in cmdlet Get-ChildItem.
As a very basic example:
...
param
(
[string] $sourceDirectory = ".",
[string] $fileTypeFilter = "*.log",
[boolean] $recurse = $true
)
Get-ChildItem $sourceDirectory -recurse -filter $fileTypeFilter |
...
How does one conditionally add the -recurse flag to Get-ChildItem without having to resort to some if/else statement?
I thought perhaps one could just substitute the -recurse in the Get-ChildItem statement with a $recurseText parameter (set to “-recurse” if $recurse were true), but that does not seem to work.
A couple of things here. First, you don’t want to use [boolean] for the type of the recurse parameter. That requires that you pass an argument for the Recurse parameter on your script e.g.
-Recurse $true. What you want is a [switch] parameter as shown below. Also, when you forward the switch value to the -Recurse parameter on Get-ChildItem use a:as shown below: