Reputation: 13
Sorry, this is difficult to explain. I have a long, piped, etc. command like this:
param (
[alias("r")]
[Parameter(Mandatory = $false)]
[switch]$recurse = $false,
[...]
$allFiles = Get-ChildItem $folder | Where-Object { $_.CreationTime -ge [DateTime]::Now.AddHours($hoursOld) } |
ForEach-Object {
[...]
And there is another way to run Get-ChildItem, which is with the -recurse option. I only know how to write the entire command all over again, but with the "-recurse" option, and wrap both ways in an if/else...
Is there a way to include that -recurse after gci only if the -r (switch command line option, alias for $recurse) is $True?
ex:
$allFiles = Get-ChildItem $folder -recurse | Where-Object { $_.CreationTime -ge [DateTime]::Now.AddHours($hoursOld) } |
ForEach-Object {
[...]
PS C:\PSScripts> $psversiontable
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 6.3.9600.18728
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
Upvotes: 1
Views: 557
Reputation: 10019
Switches can be $true
or $false
. Exclusion is the same as $false
, and inclusion is the same as $true
. However, you can override this by being explicit:
$allFiles = Get-ChildItem $folder -recurse:$recurse | Where-Object ...
This takes the value of $recurse
, and applies it to -recurse
. So you have -recurse:$true
when $recurse
is included, and -recurse:$false
when it is not.
Upvotes: 3