Get-ChildItem recurse as a parameter in PowerShell
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:
param ( [string] $sourceDirectory = ".", [string] $fileTypeFilter = "*.log", [switch] $recurse)get-childitem $sourceDirectory -recurse:$recurse -filter $fileTypeFilter | ...
The PowerShell V1 way to approach this is to use the method described in the other answers (-recurse:$recurse), but in V2 there is a new mechanism called splatting that can make it easier to pass the arguments from one function to another.
Splatting will allow you to pass a dictionary or list of arguments to a PowerShell function. Here's a quick example.
$Parameters = @{ Path=$home Recurse=$true}Get-ChildItem @Parameters
Inside of each function or script you can use $psBoundParameters
to get the currently bound parameters. By adding or removing items to $psBoundParameters
, it's easy to take your current function and call a cmdlet with some the functions' arguments.
I hope this helps.
I asked a similar question before... My accepted answer was basically that in v1 of PowerShell, just passing the named parameter through like:
get-childitem $sourceDirectory -recurse:$recurse -filter ...