Home > Software design >  Can you dynamically set an attribute in a Powershell cmdlet call?
Can you dynamically set an attribute in a Powershell cmdlet call?

Time:12-28

I am not sure if this is possible, but I am wondering if there's an elegant "dynamic" way to use or not an attribute when using a cmdlet in Powershell.

For instance, in the code below, how can i set the -directory attribute to be present or not, depending on some conditions?

gci $folder_root -recurse -directory | ForEach{ 
  # do something
}

CodePudding user response:

You can conditionally add parameter arguments to a call through a technique called splatting.

All you need to do is construct a dictionary-like object and add any parameters you might want to pass to the call there:

# Create empty hashtable to hold conditional arguments
$optionalArguments = @{}

# Conditionally add an argument
if($somethingThatMightBeTrue){
    # This is equivalent to having the `-Directory` switch present
    $optionalArguments['Directory'] = $true
}

# And invoke the command
Get-ChildItem $folder_root -Recurse @optionalArguments

Notice that any variable that we splat is specified with a @ instead of $ at the call site.

  • Related