Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: conditional flag based on a local variable

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

like image 869
Piotr L Avatar asked Jul 17 '26 15:07

Piotr L


2 Answers

$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

Why?

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.

like image 73
briantist Avatar answered Jul 20 '26 08:07

briantist


This should do it:

$Files = Get-ChildItem $RootPath -Name $FileMask -Recurse:$IncludeSubfolders
like image 33
EBGreen Avatar answered Jul 20 '26 09:07

EBGreen