There is a variable in my PowerShell script called $IncludeSubfolders (either 0 or 1)
Depending on its value, I would like to call Get-ChildItem method either with or without the -Recurse option.
Currently, my code looks like this:
if($IncludeSubfolders) {
$Files = Get-ChildItem $RootPath -Name $FileMask -Recurse
} else {
$Files = Get-ChildItem $RootPath -Name $FileMask
}
I would like to avoid this branching and just have a single line of code calling Get-ChildItem with -Recurse flag if $IncludeSubfolders is 1 or without it if it is 0.
Is this achievable? How?
Powershell version 5.0.10586.117
$IncludeSubfolders should ideally be a boolean value, not an integer, but it can be converted easily.
Even if you must keep it an integer, the code is the same.
$Files = Get-ChildItem $RootPath -Name $FileMask -Recurse:$IncludeSubfolders
Because -Recurse is a Switch parameter, which is a special type of boolean in which an explicit value is not needed. Present makes it true, absent makes it false. But all switch parameters can take an explicit value as well, using the colon directly after it.
If you try to use a non-boolean value in an expression where a boolean is expected, PowerShell will do its best to coalesce that value to boolean, and in this case 0 will become $false while 1 will become $true.
This should do it:
$Files = Get-ChildItem $RootPath -Name $FileMask -Recurse:$IncludeSubfolders
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With